Javascript: .push is not a function
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;
The problem here is that array.push(b)
returns the new length of the array
. So after calling combine(current, array[i])
for the first time, the length of your array will be returned and current
becomes an integer
, and since current
is the passed to combine(current, array[i])
in the next iteration, JavaScript throws the TypeError
. Your implementation for combine(current, array[i]
should look like this:
function(array, b) {
array.push(b);
return array;
}
Return just the Array, see below:
http://jsfiddle.net/0en82r7t/1/
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(reduce(arrays,function(array,b){
array.push(b);
return array;
}));
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) {
array.push(b)
return array;
}));
array.push does not return an Array, but instead the new length
Also, I know this is just a test, but in the future and in real app development don't name an Array
array. Use more verbose and clear naming, examples: numGroupArray, datesArray, timeArray, tagsArray...