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

AIon picture AIon · Jul 2, 2017 · Viewed 10.5k times · Source

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

Answer

Ori Drori picture Ori Drori · Jul 2, 2017

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);