Do you see the problem with this solution?

Hi guys, I followed the instructions here to get an understanding of how to do this, but I’m failing one of the tests to pass the problem. The last array with all negatives is coming in as 0 not -3.

Do you see any issues? I noticed there are many ways to solve this and one is according to Google search Math.max(), but I wasn’t sure how to apply it so I just used the article (which gives a much better explanation than even the “hint”)

Thanks

Your code so far


function largestOfFour(arr) {
var largestNumber = [0,0,0,0];
for (var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
  for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {
    if (arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {
      largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
    }
  }  
}

return largestNumber;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

if the array has only negative numbers, the biggest number will wrongly result in 0

you need to start in a different way

I see, thanks. I just replaced it with [0,0,0,-100] and it worked :+1:

that’s really hacky, and what will happen if he biggest number is -101?

maybe try to find a solution that will always work

1 Like

You could try this.

var largestNumber = [0,0,0, -Infinity];

1 Like

Thank you @jwilkins.oboe .

@ilenia I looked into it and saw that the Math.max solution wouldn’t be as helpful for me because I need more practice with for loops before I go into learning the other functions.

function largestOfFour(arr) {
  return arr.map(Function.apply.bind(Math.max, null));
}

Not saying above would be the most complicated solution, but it seems for loops are more important to get down (based on my rookie observation).

1 Like

then you can find a solution that will always work using loops

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.