How to use reduce to find maximum from array of objects with array of objects

If I have the following

arr = [
{key: "a",
values : [{key: "aa", value: 2}, {key: "bb", value: 5}]},
{key: "b",
values : [{key: "cc", value: 7}, {key: "dd", value: 3}]}
]

How to use reduce in javascript to find the maximum from the nested objects? The answer should be 7 in the above case.

I currently am able to use a loop to achieve this:

let max = 0;
let findDataMax = function(d) {
  for (let i = 0; i < d.length; i++) {
    let currArr = d[i].values;
    let tempArr = []
    currArr.forEach((d) => tempArr.push(+d.value));
    if (Math.max(...tempArr) > max) {
      max = Math.max(...tempArr);
    }
  }
}

let arr = [
  {key: "a", values : [{key: "aa", value: 2}, {key: "bb", value: 5}]},
  {key: "b",values : [{key: "cc", value: 7}, {key: "dd", value: 3}]}
];
findDataMax(arr);
console.log(max);

Answer

I would prefer to use other methods other than reduce for this, but if you have to, then you can set the accumulator as -Infinity to begin with (this way any value compared with the accumulator will be bigger than -Infinity). For each object in your array, you can find the max by mapping the array of values to an array of value numbers from each object, and then spreading these numbers into a call to Math.max(). You can then compare whether or not this is larger than the current maximum, and if it is, return that as the new value to use as the accumulator, otherwise, use the old accumulator value:

const arr = [ {key: "a", values : [{ key: "aa", value: 2}, { key: "bb",value: 5}]}, {key: "b", values : [{ key: "cc", value: 7}, { key: "dd", value: 3}]} ];

const max = arr.reduce((max, {values}) => {
  const newMax = Math.max(...values.map(({value}) => value));
  return newMax > max ? newMax : max;
}, -Infinity);
console.log(max);

As previously mentioned, I would probably use a different approach to .reduce(), such as .flatMap() to grab all object value numbers, which you can then spread into a call to Math.max():

const arr = [ {key: "a", values : [{ key: "aa", value: 2}, { key: "bb",value: 5}]}, {key: "b", values : [{ key: "cc", value: 7}, { key: "dd", value: 3}]} ];

const max = Math.max(...arr.flatMap(({values}) => values.map(({value}) => value)));
console.log(max);

Leave a Reply

Your email address will not be published. Required fields are marked *