arr.reduce method return accumulator the first argument. but why last value returned [duplicate]

5 hours ago 1
ARTICLE AD BOX

arr.reduce method return the accumulator which is the first argument. So why the last value of array is return in my code.

The problem which I was trying to solve is

enter image description here

Correct solution:

function groupByid(arr){ return arr.reduce( (obj, value) => { obj[value.id] = value; return obj; }, {} ); } let users = [ {id: "john", name: "John Smith", age: 20}, {id: "ann", name: "Ann Smith", age: 24}, {id: 'pete', name: "Pete Peterson", age: 31}, ]; let userById = groupByid(users); console.log(userById);

Wrong solution: But why the last value of array is returned. instead of first argument of arr.reduce method because arr.reduce method return the first computed argument?

function groupByid(arr){ return arr.reduce( (obj, value) => obj[value.id] = value, {} ); } let users = [ {id: "john", name: "John Smith", age: 20}, {id: "ann", name: "Ann Smith", age: 24}, {id: 'pete', name: "Pete Peterson", age: 31}, ]; let userById = groupByid(users); console.log(userById);
Read Entire Article