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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With