Return Largest Number in an Array help

Hi everyone,

I keep getting the error “newArray.push is not a function”, but I’m not sure why. I defined the newArray as an array. Can someone let me know what I’m doing wrong?

Thanks!

function largestOfFour(arr) {

var newArray = [];
var largest = 0;

for (var i = 0; i<arr.length; i++) {

largest = arr[i].reduce(function(a, b) {

return Math.max(a,b);

});

newArray = newArray.push(largest);

}
return newArray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

I keep getting the error “newArray.push is not a function”, but I’m not sure why.

While indeed you defined the newArray as an array, at line 13:

newArray = newArray.push(largest);

You’re replacing it with the new length value of newArray which will be 1 (as this is what .push() returns).

###Here is your code in action while logging the value of newArray:

####What is happening here:

Loop i = 0: NewArray is updated to 1.
Loop i = 1: Uncaught TypeError.

So when you use the push method, just push the value into an array without the assignment operator.

newArray.push(largest);


As MDN documents:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Read more about .push()…

Anything else let me know,
Goodluck.

Thank you both! That makes a lot more sense!