The code is find the max value
- How this code work
// this is original code
const items = [
{ id: 0 },
{ id: 1 },
{ id: 2 }
]
function id(items) {
const maxId = items.reduce((maxId, items) =>
Math.max(items.id, maxId), -1
)
return maxId + 1
}
console.log(id(items)) // I get 3
The reduce methods callback (maxId, items) => Math.max(items.id, maxId), -1
I can not figure out what is this, it just return something, -1
I never seem this syntax ever.
A comma between two value, what I expect is return [ , ]
or ( , )
- Why this code get different result
I also tried this below, I think its same code above. But result is not same.
// I changed something, I add { return something in reduce callback }
const items = [
{ id: 0 },
{ id: 1 },
{ id: 2 }
]
function id(items) {
const maxId = items.reduce((maxId, items) => { // Here
return Math.max(items.id, maxId), -1 // add
} // { return }
)
return maxId + 1
}
console.log(id(items)) // I get 0