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

I am testing a prototype of a method in the Chrome console and getting an unexpected result regarding Array.prototype.reduce ()

For example, for an example below

let a = [["a",1],["b",1],["c",1]];

let result = a.reduce((acc, e) => acc[e[0]]=e[1], {});

the result that I expected would be

{
  "a": 1,
  "b": 1,
  "c": 1
}

but instead I get a value of 1

+4
source share
4 answers

You also need to return the battery at 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)
Run codeHide result

You can also use the destructuring assignment for the second parameter to get the first and second elements 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)
Run codeHide result
+5
source

Since you need to return the accumulated object from the callback:

let result = a.reduce((acc, e) => {
  acc[e[0]] = e[1];
  return acc;
}, {});
+3
source

reduce (. sp00m), , acc . ( , , acc[e[0]] = e[1] .) reduce , .

forEach:

let a = [["a",1],["b",1],["c",1]];
let result = {};
a.forEach(e => result[e[0]] = e[1]);
+3

:

let result = a.reduce((acc, e) => {acc[el[0]]=e[1]; return acc}, {});

:

acc[e[0]]=e[1] //this returns 1 not the acc
0

Source: https://habr.com/ru/post/1684361/


All Articles