Returns the largest number in arrays

function largestOfFour(arr) {

    for(var i = 0; i < arr.length; i++) {
      var largest = Math.max.apply(Math, arr[i]);
      return largest;
    }
}

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

I need to return the largest number from each of them. When I run my code using console.log, it prints the largest number of each array, but when I return it, only the largest number from array 0 is returned. Can someone help me with this?

+4
source share
3 answers

return exits the function, you need to create an array and add the largest values ​​to it.

function largestOfFour(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    result.push(Math.max.apply(Math, arr[i]));
  }
  return result;
}

document.body.innerHTML = largestOfFour([
  [4, 5, 1, 3],
  [13, 27, 18, 26],
  [32, 35, 37, 39],
  [1000, 1001, 857, 1]
]);
Run code
+5
source

You can also use mapinsteadfor

function largestOfFour(arrs) {
  return arrs.map(function(arr){
    return Math.max.apply(null, arr);
  });
}

document.body.innerHTML = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Run code
+1
source

Another way is to use Array.prototype.reduce()

function largestOfFour(arr) {
    return arr.reduce(function(p, c, index, arr){
      p.push(Math.max.apply(null, c));
      return p;
    }, []);
}
0
source

All Articles