Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array.prototype.reduce() reduces in signe nubmer instead of object

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

like image 801
Xipo Avatar asked Dec 19 '22 04:12

Xipo


1 Answers

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)
like image 145
Nenad Vracar Avatar answered Dec 24 '22 02:12

Nenad Vracar