0

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, value) => {
  return accumulator + value;
}, 0);

console.log(sum); // 13

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.