Reputation: 1823
I'm testing a prototype of a method on Chrome Console and getting an unexpected result regarding Array.prototype.reduce()
Eg for the example bellow
let a = [["a",1],["b",1],["c",1]];
let result = a.reduce((acc, e) => acc[e[0]]=e[1], {});
the result I expected to have is
{
"a": 1,
"b": 1,
"c": 1
}
but instead I get the value 1
Upvotes: 4
Views: 96
Reputation: 1075159
While you can use reduce
for this (see sp00m's answer), it's not a great fit, and it's clunky and easily forgotten to return acc
from the callback every time. (And in your case, because you didn't and used a concise arrow, you were returning the result of acc[e[0]] = e[1]
at each stage.) reduce
is useful for when the accumulator changes through the course of the reduction.
This is really just a case for forEach
:
let a = [["a",1],["b",1],["c",1]];
let result = {};
a.forEach(e => result[e[0]] = e[1]);
Upvotes: 3
Reputation: 122087
You also need to return accumulator in each iteration.
let a = [["a",1],["c",1],["d",1]];
let result = a.reduce((acc, e) => (acc[e[0]]=e[1], acc), {});
console.log(result)
You could also use destructuring assignment on second parameter to get first and second element of each array.
let a = [["a",1],["c",1],["d",1]];
let result = a.reduce((acc, [a, b]) => (acc[a] = b, acc), {});
console.log(result)
Upvotes: 5
Reputation: 6931
You should change your code to:
let result = a.reduce((acc, e) => {acc[el[0]]=e[1]; return acc}, {});
Why:
acc[e[0]]=e[1] //this returns 1 not the acc
Upvotes: 0
Reputation: 48837
Because you need to return the accumulated object from the callback:
let result = a.reduce((acc, e) => {
acc[e[0]] = e[1];
return acc;
}, {});
Upvotes: 3