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

2
  • because largestNum has 0's as min values, but values could be negative as well, thus your assumption that 0 is the min. value is incorrect . Commented Aug 21, 2018 at 14:05
  • in negative smaller one is the largest. -1 is the largest number in negative Commented Aug 21, 2018 at 14:07

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.