Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I return the result of pushing to the accumulator in a .reduce() function?

simple example, want to return an array of arrays. For each name in 'peeps' I want to push an array with the word 'hello' into the accumulator.

const peeps = ['sally', 'nick', 'dave'];

return peeps.reduce((acc, val) => {
     return acc.push(['hello'])
  }, []);

It keeps saying that acc.push() is not a function.

Can someone please help me understand why this does not work.

like image 709
Josh Pittman Avatar asked Dec 01 '22 12:12

Josh Pittman


2 Answers

You use Array#push

The push() method adds one or more elements to the end of an array and returns the new length of the array.

this returns the length of the array after pushing. Then the accumulator value is a number, not an array

return acc.push(['hello']) // 1

Solution 1: Return the array instead of the result of pushing.

const peeps = ['sally', 'nick', 'dave'];

console.log(peeps.reduce((acc, val) => {
    acc.push(['hello']);
    return acc;
}, []));

Solution 2: Use Array#concat.

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

I would avoid using it with large amounts of data though, as it is a lot less efficient than push. jsPerf

const peeps = ['sally', 'nick', 'dave'];

console.log(peeps.reduce((acc, val) => acc.concat([['hello']]), []));

Solution 3: Use Array#map. This works best, if the result array should have the same length as the given array.

The map() method creates a new array with the results of calling a provided function on every element in this array.

const peeps = ['sally', 'nick', 'dave'];

console.log(peeps.map(val => ['hello']));
like image 164
Nina Scholz Avatar answered Dec 05 '22 13:12

Nina Scholz


Try this instead:

const peeps = ['sally', 'nick', 'dave'];

return peeps.reduce((acc, val) => {
    acc.push(['hello']);
    return acc;
}, []);

push does not return acc, you have to do it manually.

like image 29
fafl Avatar answered Dec 05 '22 14:12

fafl