Return Largest Number in an Array help

Return Largest Number in an Array help
0

#1

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]]);


#2

Your line #13 should read

newArray.push(largest);

instead of:

newArray = newArray.push(largest);

#3

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.


#4

Thank you both! That makes a lot more sense!


#5

Also, since you are using the higher order function reduce, you could also use map instead of the for loop. See below:

function largestOfFour(arr) {
  var newArray = arr.map(function(items) {
    return items.reduce(function(a,b) {
      return Math.max(a,b);
    });
  });
  return newArray; 
}

And the above could be taken another step to simplify the code:

function largestOfFour(arr) {
  return arr.map(function(items) {
    return items.reduce(function(a,b) {
      return Math.max(a,b);
    });
  });
}

And if you really want to simplify, you can use the arrow function syntax with the above:

function largestOfFour(arr) {
  return arr.map((items) => items.reduce((a,b) => Math.max(a,b)));
}