Xipo
Xipo

Reputation: 1823

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

Upvotes: 4

Views: 96

Answers (4)

T.J. Crowder
T.J. Crowder

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

Nenad Vracar
Nenad Vracar

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

Kocur4d
Kocur4d

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

sp00m
sp00m

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

Related Questions