Using the reduce function to return an array

Why is this, when I want to use the push function inside the reduce function to return a new array, I get an error message. However, when I use the concat method inside the reduction function, it returns a new array without problems.

All I'm trying to do is pass an array to the reduction function and return the same array.

var store = [0,1,2,3,4]; var stored = store.reduce(function(pV,cV,cI){ console.log("pv: ", pV); return pV.push(cV); },[]); 

This returns an error. But when I use concat:

 var store = [0,1,2,3,4]; var stored = store.reduce(function(pV,cV,cI){ console.log("pv: ", pV); return pV.concat(cV); },[]); 

It returns the same array.

Any ideas why?

+7
javascript arrays reduce
source share
3 answers

push returns the new length of the array.

You need a source array.

So change the code as shown below.

 var store = [0,1,2,3,4]; var stored = store.reduce(function(pV,cV,cI){ console.log("pv: ", pV); pV.push(cV); return pV; // ********* Important ****** }, []); 

concat returns a new array combining the elements of the provided array and the concatenated elements. therefore it works.

+15
source share

Just for the sake of completeness, and for the next person who happens to be on this issue, what you do is usually achieved using map , which, as stated in the docs

matches the called callback function once for each element of the array in order and builds a new array from the results

Compare this with the description of reduce :

The reduce () method applies the function to the accumulator and each value of the array (from left to right) to reduce it to a single value .

(Emphasis mine) So you see, although you can manipulate reduce to return a new array, this common use is to reduce the array to a single value.

So for your code this would be:

 var store = [0,1,2,3,4]; var stored = store.map(function(pV){ console.log("pv: ", pV); return pV; }); 

Much easier than trying to restore a new array using push or concat inside the reduce function.

+3
source share

The Array.prototype.push method returns the new length of the array.

The Array.prototype.concat method inserts a new element into the array and returns the array back so that it can be processed. This is what you need to do to reduce: pass the modified array to the next iteration.

+1
source share

All Articles