简体   繁体   中英

javascript reduce find max in array of arrays

I want to find the max number among the first and second elements of each array inside the array of arrays separately:

 function largestOfElements(mainArray) { return mainArray.map(function(subArray) { return subArray.reduce(function(previousLargestNumber, currentLargestNumber) { return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber; }, 0); }); } console.log(largestOfElements([ [], [13, 47], [38, 35], [24, 34] ])); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

the current way returns an array of the largest numbers in each array. How can I return the largest of the first elements and the largest of the second elements? the expected result will be:

[38, 47]

You can use the function reduce .

  • The initial value for the function reduce are the min values to start getting the highest values.
  • Check for the length of the current array.
  • Use destructuring assignment to get the first and second value [first, second].
  • Check the current value against first and second respectively to get the highest.

 var array = [ [], [13, 47], [38, 35], [24, 34] ]; var result = Object.values(array.reduce((a, c) => { if (c.length) { var [first, second] = c; if (first > af) af = first; if (second > as) as = second; } return a; }, {f: Number.MIN_VALUE, s: Number.MIN_VALUE})); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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