Skip to content
Advertisement

Reduce nested array maximum values to a single array

I am trying to find a way to reduce the max values of specific positions/indexes within nested arrays into a single array.

Given:

const myArr = [[105,87,171],[113,192,87],[113,87,87],[113,87,87]]

Expected return value:

[113,192,171]

Actual return value:

[113,87,87]

Using the following code, I’m getting the above return value.

const highest = myArr.reduce((previous, current) => {
  return current > previous ? current : previous;
});

Why am I only getting the max value for the first position, and not the remaining two positions of the nested arrays?

Advertisement

Answer

You need to compare the elements in subarrays by index.

const myArr = [[105,87,171],[113,192,87],[113,87,87],[113,87,87]]

const highest = myArr.reduce((previousArr, currentArr) => {
    return previousArr.map((item, index) =>
        Math.max(item, currentArr[index])
    )
});

console.log(highest)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement