Comparing Values of a Multi-dimensional Array in JS
I would like to compare the values in a multi-dimensional array. i.e [[1, 2], [3,10], [3, 3]] Should return me 13 as it is the highest total of the given array.
II have managed to add the individual elements.
const arr = [3, 10];
const sum = arr.reduce((accumulator, va开发者_运维技巧lue) => {
return accumulator + value;
}, 0);
console.log(sum); // 13
const k = [[1, 2], [3,10], [3, 3]]
now use map to terverse the internal array
const sumOfInternal = k.map((item) => item.reduce((acc,cur) => acc+cur))
//sumOfInternal [3, 13, 6]
const output = Math.max(...sumOfInternal)
//output will be 13
You can use the Math.max function to compare values.
Also, you can use the second argument of Array.prototype.reduce to indicate an initial value for the accumulator.
Here, we'll use two nested reducer functions. One will add up the elements, like you did in your example, and the other will compare the current value to the previous maximum. We'll use second argument to set the initial value for max
to -Infinity
.
const arr = [[1, 2], [3,10], [3, 3]]
const result = arr.reduce((max, current) => Math.max(current.reduce((sum, value) => sum + value, 0), max), -Infinity)
精彩评论