2

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);

3
  • Because adding , acc will return acc object. only acc[key] = value will return value not acc. Commented Jun 10, 2020 at 13:56
  • The second snippet have error Commented Jun 10, 2020 at 13:58
  • you always have to accumulate into you acc otherwise you are just returning the one value it's like having a for loop and returning the last value of it instead of aggregating all of them Commented Jun 10, 2020 at 13:59

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.