Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  34] [ 5]  / answers: 1 / hits: 21664  / 9 Years ago, fri, october 16, 2015, 12:00:00

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.


More From » arrays

 Answers
29

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;

[#64710] Wednesday, October 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alenaautump

Total Points: 87
Total Questions: 109
Total Answers: 109

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;