"Return Largest Numbers in Array" Algorithm exercise

I just did the “Return Largest Numbers in Arrays” Algorithm Challenge on the platform. The goal of the exercise return an array consisting of the largest number from each provided sub-array. I had the following solution to the problem:

function largestOfFour(arr) {
  var newArr = arr.map(function(val) {
    val.reduce(function(a, b) {
      return Math.max(a, b);
    });
  });
  return newArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

This output was [null,null,null,null].

The correct code was:

function largestOfFour(arr) {
  return arr.map(function(val) {
   return val.reduce(function(a, b) {
     return Math.max(a, b);
    });
  });
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

The result was: [5, 27, 39, 1001]

I do not get why my code didn’t work.

Your map's callback function isn’t returning the result of the reduce call in it.

1 Like

Ha! Thanks for pointing that out! As a rewrite, my code would therefore be:

function largestOfFour(arr) {
  var newArr = arr.map(function(val) {
    return val.reduce(function(a, b) {
      return Math.max(a, b);
    });
  });
  return newArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Which works! That was super helpful!