Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  32] [ 4]  / answers: 1 / hits: 106462  / 8 Years ago, tue, february 16, 2016, 12:00:00

Why is it that when I want to use the push function inside the reduce function to return a new array I get an error. However, when I use the concat method inside the reduce function, it returns a new array with no problem.



All I'm trying to do is pass an array to the reduce 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?


More From » arrays

 Answers
24

push returns the new length of the array.



What you need is the initially provided array.



So change the code as 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 the new array combining the elements of the provided array and concatenated elements. so it works.


[#63303] Saturday, February 13, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;