Finding the minimum value of a nested object property

Viewed 336

I have an object that looks like this:

const yo = {
  one: {
    value: 0,
    mission: 17},
  two: {
    value: 18,
    mission: 3},
  three: {
    value: -2,
    mission: 4},
}

I want to find the minimum value of the mission prop within the nested objects. This line works to find the minimum value of the nested value prop and returns -2:

const total = Object.values(yo).reduce((t, {value}) => Math.min(t, value), 0)

But when I try the same thing for the mission prop, it returns 0 when it should be 3:

const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), 0)

Is there something that I am missing or doing wrong?

2 Answers

In this case, map is enough.

const yo = {
  one: {
    value: 9,
    mission: 17
  },
  two: {
    value: 18,
    mission: 6
  },
  three: {
    value: 3,
    mission: 4
  },
}

const total = Object.values(yo).map(({ mission }) => mission);
console.log(Math.min(...total));

You are passing 0 as the initial value of accumulator i.e t. 0 is less than all the mission values. So you need to pass the greatest value i.e Infinity as second argument of reduce().

const yo = {
  one: {
    value: 0,
    mission: 17},
  two: {
    value: 18,
    mission: 3},
  three: {
    value: -2,
    mission: 4},
}
const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), Infinity);
console.log(total)

Related