0
  function largestOfFour(arr) {
    var lista = [];
    var max = 0;
    for (var x = 0; x < arr.length; x++) {
      for (var y = 0; y < arr[x].length; y++){
        if (arr[x][y] > max) {
        max = arr[x][y];
        }
      lista[x] = max;
      }
    }
    return lista;
  }

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

^ generates the following array: [27,27,39,1001], but the answer is: [27,5,39,1001]

My function correctly shows the maximum number in each sub-array, EXCEPT the 2nd subarray. I don't understand what part of my code is wrong.

0

3 Answers 3

1

You never reset the max variable. You need to reset it at on each iteration of the outer for loop. (If the sub array with 1001 had been the first sub array your result would've been [1001, 1001, 1001, 1001].)

function largestOfFour(arr) {
  var lista = [];
  var max;
  for (var x = 0; x < arr.length; x++) {
    max = 0;  // <-- add this line
    for (var y = 0; y < arr[x].length; y++){
      if (arr[x][y] > max) {
        max = arr[x][y];
      }
    lista[x] = max;
    }
  }
  return lista;
}
    
console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

Incidentally, you can implement the same thing with fewer lines of code if you do something like this:

function largestOfFour(arr) {
  return arr.map(function(a) {
    return Math.max.apply(Math,a);
  });
}

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

Or even shorter with arrow functions:

var largestOfFour = arr => arr.map(a => Math.max.apply(Math,a));

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

Sign up to request clarification or add additional context in comments.

Comments

1

If you want, you can write this function in one line. You can apply .map() function on your array, and return the max element of each sub array by using Math.max() method.

function largest(array) {
  return array.map(a => Math.max(...a));
}

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

You should take a look about functional programming, it can be really useful.

Comments

0

You don't reset max Move its def inside the first loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.