简体   繁体   中英

Using reduce() within map() on array of arrays

I'm working on a freecodecamp challenge, and am wondering why my code doesn't work and how to correct it.

The objective is to "Return an array consisting of the largest number from each provided sub-array."

My attempt was to map the input array using reduce as the map function:

function largestOfFour(arr) {
    arr = arr.map(function(innerArray){
       innerArray = innerArray.reduce(function(previousValue,currentValue){
           return currentValue > previousValue ? currentValue : previousValue;
       });
    });
    return arr;
}

console.log(largestOfFour([[4, 5, 1, 3],[1, 2, 3, 4]]));

Currently the output is: [undefined, undefined]

How should I fix my code?

Inside the map callback, you should return the result of reduce :

function largestOfFour(arr) {
  return arr.map(function(innerArray){
    return innerArray.reduce(function(previousValue,currentValue){
      return currentValue > previousValue ? currentValue : previousValue;
    });
  });
}

Note there are shorter ways of doing that .

There's an easier way

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

Math.max can be called with multiple arguments, as in Math.max(3,4,5,6) would return 6 .

using apply we can pass an array of arguments to a function, as in .apply(thisValue, [3,4,5,6]) and do the same thing.

Since there's an array of arrays, we can map the outer array, and return the result of Math.max.apply(thisValue, innerArray) , and since the thisValue is unimportant here, just passing null is fine.

Yet another way to solve this

 function largestOfFour(arr) { return arr.map(function(innerArray) { // sort innerArray ascending return innerArray.sort(function sort(a, b) { return a > b; }).pop(); // << get the last element (the max) }); } var result = largestOfFour([ [4, 5, 1, 3], [1, 2, 3, 4] ]); console.log(result); document.write(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM