How to use reduce to transform an array into an object?

Viewed 306

Thanks to another SO thread, I have managed to transform an array of arrays into an object thanks to reduce(). However, I don't understand why it works.

Could someone please explain to me why I can't only write => acc[key] = value, {} ? This syntax makes sense to me. But it returns 21! It only works if I add ,acc between my object assignation and my starting value {}. Also, ESLint claims it is an unexpected use of comma operator.

const myArray = [["player1", 30], ["player2", 21]];
const obj = myArray.reduce((acc, [key, value]) => (acc[key] = value, acc), {});

console.log("obj : ", obj);

I have also written this. It works well as well, but I'm still wondering why the first script works:

const myArray = [["player1", 30], ["player2", 21]];
const obj = myArray.reduce((acc, [key, value]) => Object.assign(acc, {[key]: value}),{});

console.log("obj : ", obj);

1 Answers

When you use reduce() you need to return the accumulator acc from the callback

Second thing you need to understand is implicit return. When you use arrow function => without {} and return the value after => becomes the return value of the function.

Another thing you need to understand is comma operator. When you use comma operator between two or more expressions it evaluates to the last one.

console.log(("first", "second", "third"))

In the above snippet the whole expression ("first", "second", "third") evaluates to "third".

Same happens in ur case (acc[key] = value, acc) evaluates to acc.

const myArray = [["player1", 30], ["player2", 21]]
const toObj = myArray.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
})
console.log(toObj)

Could someone please explain to me why I can't only write => acc[key] = value, {} ?

I mentioned above when you use reduce() you need to return acc from ur function. So then you use the above way acc[key] = value gets returned from each iteration. and acc[key] = value will always evaluate to value so the whole reduce method returns the last value which is 21

Related