Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.push is not a function - when working with reduce [duplicate]

Can someone please help me understand whats going on here?

let firstArray = []; firstArray.push(1); firstArray.push(1); firstArray.push(1); console.log("firstArray", firstArray); // result [ 1, 1, 1 ] - as expected.    let secondArray = [1, 2, 3].reduce((acc, item) => {      console.log("acc", acc);     console.log("typeof acc", typeof acc);      // on first passing, the accumulator (acc) is Array[] == object.     // on the second passing the acc == number.      // but why?     /// i expect to get [1,1,1] as my secondArray.     return acc.push(1);  }, []);  console.log("secondArray", secondArray);  

the program crashes with "acc.push is not a function"

accumulator.push is not a function in reduce

And inspecting the first logged accumulator shows that we have the push method - it's a real function:

array.push not working with reduce

like image 751
AIon Avatar asked Jul 02 '17 21:07

AIon


People also ask

Can we push function in array?

push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.

Is not a function at Push?

The "push is not a function" error occurs when the push() method is called on a value that is not an array. To solve the error, convert the value to an array before calling the method, or make sure to only call the push() method on valid arrays. Here is an example of how the error occurs.

Does push change array?

The push() method adds new items to the end of an array. The push() method changes the length of the array.

What is the opposite of array push?

pop(): We use pop JavaScript to remove the last element in an array. Moreover, this function returns the removed element. At the same, it will reduce the length of the array by one. This function is the opposite of the JavaScript array push function.


1 Answers

The return value of Array#push is the new length of the array after the push. This means that in the second iteration acc is a number, which doesn't have the push method.

The fix is simple - separate the push and return statements:

const secondArray = [1, 2, 3].reduce((acc, item) => {      acc.push(1);        return acc;  }, []);    console.log(secondArray);
like image 137
Ori Drori Avatar answered Sep 24 '22 08:09

Ori Drori