Array.push is not a function - when working with decrement
Can someone please help me understand what is 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"
And checking the first one registered accumulator
shows that we have a push method - this is a real function:
+3
source to share
1 answer
The return value Array#push
is the new length of the array after clicking. This means that acc
there is a number in the second iteration that does not have a 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);
+11
source to share