Using Huge Negative Number to Compare

Hello,

I have successfully made a function which takes an array of arrays and returns a new array with each of the largest numbers from the nested arrays.

However, to achieve this I have had to set my ‘currHigh’ variable to negative 1 million to avoid issues with the occurrence negative numbers within the arrays.

Please could someone offer up a more air-tight method that would not falter should -1000001 or larger appear in any of the arrays?

Kindest regards :slight_smile:

function largestOfFour(arr) {
  
  const newArr = [];

  for (let each of arr) {
    let currHigh = -1000000;
    for (let i = 0; i < each.length; i++) {
      if (each[i] > currHigh) {
        currHigh = each[i];
      }
    }
    newArr.push(currHigh);
  }
  
  return newArr;
}

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

you can avoid using a “magic number” here if you adjust a tiny bit your logic.

It involves using a number that you are sure is in the array

2 Likes

There is a concept of -Infinity in JavaScript. But using it here would be lazy. Suggest you think about how you would do this another way.

Just to be clear;

You response to me asking how I can do this another way is to look for another way? :joy:

this is an other way

!!! Null !!!

Thank you :slight_smile:

Not sure how you got that meaning from my answer. I mentioned that you can use -Infinity but that doing so would be lazy. And then I said I suggest you find yet another way. But again, you seem intent on just writing solutions, so pls go ahead and use the -Infinity method if it pleases you.

No worries, mate.

Someone gave an answer that helped.

Cheers :+1:

What do you mean? null is not in the array. I meant to use something you have there. You don’t have null

1 Like

@leedsleedsleedsleeds Just to be clear @hbar1st answered your exact question. Use Infinity (-Infinity) or Number.NEGATIVE_INFINITY if you want an infinite negative number.

But as already pointed out you do not need an infinite negative number to solve this.

3 Likes

You can set the value of currHigh with the first element of the nested array and iterate though the nested array to compare it with rest of the elements

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