Return largest number array challenge!

Hi My code is like this
But it doesnt negative values

function largestOfFour(arr) {
// You can do this!
var finalArray = [];

for ( var i = 0 ; i < arr.length ; i++){
var number = 0;
for(var j = 0 ; j < arr[i].length ; j++){
if ( number < arr[i][j] ){
number = arr[i][j];

}

}

   finalArray.push(number);

}

return finalArray;
}

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

@bahramb92 I approached this problem in the same way as you and had exactly the same problem.

This issue here is your line

var number = 0;

By setting the variable to 0, in a subarray of negative number it will always see that 0 is bigger and push this into your array.

What you need to do is find a way of resetting this variable to one of the array values instead of a fixed value. That way you are always comparing two values within the array against each other to find the highest, which removes the possibility of returning a value that isn’t in the array.

My working code is:

function largestOfFour(arr) {
  // You can do this!
  let numbersArr = [];

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

    let highestNumber = arr[i][0];

    for (let j = 0; j < arr[i].length; j++) {

      if (arr[i][j] > highestNumber) {
        highestNumber = arr[i][j];
      }

    }

    numbersArr.push(highestNumber);

  }
  console.log(numbersArr);
  return numbersArr;
}

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

Thanks for your help

ES6 for … of and reduce method helps a lot:

function largestOfFour(arr) {
  // You can do this!
  let result = [];
  for (let el of arr) {
    result.push(el.reduce((acc,cur) => Math.max(acc,cur)));
  }
  return result;
}

what does the spread operator mean here ?

Math.max doesn’t take an array, so to pass an array to it, you need to spread it into separate arguments, which is what’s being done here, takes the array and passes the elements in it to the function.

you can also slash the reduce method,
use spread operator instead in math.max, since it returns a maximum value.

function largestOfFour(arr) {
  // You can do this!
  let result = [];
  for (let el of arr) {
    result.push(Math.max(...el));
  }
  return result;
}
2 Likes

Neat solution that also taught me the difference between “for of” and “for in”.