0

myArr = ['a', 'b', 'c' ]; myArr.reduce((obj, val) => ({ ...obj, [val]: val }));

Based on my understanding, you would expect the reduce to return { a: 'a', b: 'b', c: 'c' }

What we actually get back is { 0: 'a', b: 'b', c: 'c' }

I tried putting a log inside to see what is going on with that first item, but the output is:

b c {0: "a", b: "b", c: "c"}

So now the behaviour is even more strange because we don't get any logs for the first val iteration.

0

1 Answer 1

3

let myArr = ['a', 'b', 'c' ];
let result = myArr.reduce((obj, val) => ({ ...obj, [val]: val }), {});
console.log(result);

You missed the initial value to reduce. When no initial value is supplied, reduce pops off the first element for this purpose (and indeed no iteration happens; because 1+2+3 has two additions, not three, unless you specify we have to start from 0).

The first element is "a", which deceptively becomes the misnamed obj; when you execute {..."a", b: "b"}, you will see that ..."a" expanded in the object context will yield the characters' index as the key; thus, ..."a" is equivalent to ...{0: "a"}.

Good thing you didn't try with myArr = ['hello', 'world'] - that'd be much more of a surprise, I imagine (the result from that being {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", world: "world"}).

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

1 Comment

This makes so much sense - had I tried it with a different array (like hello world as you mentioned) I'm sure I would have picked up on what was going on, but with a single character string my mind was blown. Cheers for the answer!

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.