Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Array.prototype.reduce() is not taking an empty array as accumulator?

I am trying to filter all the elements in an array which are bigger than 10 to a new array. I am intentionally not using Array.prototype.filter() since I want to learn the reduce() method. Here is the code I was playing with

var collection = [3, 5, 11, 23, 1];    // fileter all the elements bigger than 10 to a new array    var output = collection.reduce(function(filteredArr, collectionElemet) {    if (collectionElemet > 10) {      return filteredArr.push(collectionElemet);    }  }, []);

I was expecting that filteredArr would be initialized with an empty array at the time of first callback execution as it happens with many examples provided here. But when I run this code, I get the error Cannot read property 'push' of undefined, where am I messing it up? Thank you!

like image 277
segmentationfaulter Avatar asked Sep 18 '15 01:09

segmentationfaulter


People also ask

Does reduce work on empty array?

We can use reduce to flatten nested amounts into a single array. We set the initial value to an empty array and then concatenate the current value to the total.

What is array prototype reduce () useful for?

prototype. reduce() The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.

What is accumulator in reduce?

Reducer is a function that takes accumulator (which is a temporary result) and current value from iteration. It does what it needs with them, and the returned value becomes the new accumulator. When we achieve the end of the array, the accumulator is returned as the result of the reduce function.

What happens when an array is empty?

If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.


1 Answers

When you try to do return filteredArr.push(collectionElement), in essence you are returning length of filteredArr after the push operation. The push() method adds one or more elements to the end of an array and returns the new length of the array. Ref: Array.prototype.push().

You need to return the filteredArr from your anonymous function, so that it is used as the previousValue for the next call

var collection = [3, 5, 11, 23, 1];  // filter all the elements bigger than 10 to a new array  var output = collection.reduce(function(filteredArr, collectionElement) {   if (collectionElement > 10) {     filteredArr.push(collectionElement);   }   return filteredArr; }, []); 
like image 172
Paul Avatar answered Oct 23 '22 22:10

Paul