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?
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 ie t
. 0
is less than all the mission
values. So you need to pass the greatest value ie 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.