0

The code is find the max value

  1. 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 ( , )


  1. 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

T Ty
  • 190
  • 1
  • 7
  • [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#how_reduce_works_without_an_initial_value) takes two parameters, a function and a starting point ---- in the above case, the function is `(maxId, items) => Math.max(items.id, maxId)` and the starting value is `-1` – skara9 Jan 18 '22 at 04:27
  • Minus one should come outside of function callback in `array#reduce`, -1 in the first snippet is the initial value. – Hassan Imam Jan 18 '22 at 04:33
  • Thanks for reply comment, In this case, reduce takes initial value. I make mistake here. – T Ty Jan 18 '22 at 04:56

0 Answers0