Reverate
Reverate

Reputation: 183

Array.reduce - strange behaviour with objects

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.

Upvotes: 0

Views: 117

Answers (1)

Amadan
Amadan

Reputation: 198324

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"}).

Upvotes: 3

Related Questions