Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: .push is not a function

I am having a problem with my code:

var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(reduce(arrays,function(array,b){
  return array.push(b);
}));

function reduce(array,combine){
  var current = [];
  for(var i = 0;i<array.length;i += 1){
    current = combine(current,array[i]);
  }
  return current;
}
console.log(reduce([1, 2, 3, 4], function(array, b) {
  return array.push(b);
}));

// → [1, 2, 3, 4, 5, 6]

I get this error:

TypeError: array.push is not a function (line 3) 

As far as I understand, this is because it is treating the array argument as something other than an array. However, I thought I fed it the variable "current" which is an array. Can someone explain the problem? Thanks.

like image 364
Devilius Avatar asked Oct 16 '15 19:10

Devilius


People also ask

How to push function into array in JavaScript?

The arr. 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 Typeerror?

This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.

How do you create an array in JavaScript?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


1 Answers

Array.push doesn't return an array. It returns the new length of the array it was called on.

So, your return array.push(b); returns an int. That int gets passed back as array... which is not an array so it doesn't have a .push() method.

You need to do:

array.push(b);
return array;
like image 135
Rocket Hazmat Avatar answered Sep 18 '22 16:09

Rocket Hazmat