0

I'm supposed to be returning an array consisting of the largest number from each sub-array. Here is my code:

function largestOfFour(arr) {
  let largestNum = [0,0,0,0];
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] > largestNum[i]) {
        largestNum[i] = arr[i][j];
      }
    }
  }
  return largestNum;
}

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

I pass all the tests except for one.

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

should return an array. Passed

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

should return [27, 5, 39, 1001]. Passed

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) 

should return [9, 35, 97, 1000000].

largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) 

should return [25, 48, 21, -3]. Failed

If anyone would be willing to tell me what i'm doing wrong, that would be so helpful. Thank you

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44

1 Answers1

1

You can simply use Math.max on each of the sub arrays by deconstructing them:

function largestOfFour(arr) {
  return arr.map(subarr => Math.max(...subarr));
}

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

console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44