2

What would be a shorter way to write :

if (array1[0] >= array2[0] && array1[1] >= array2[1] && ...) {
do something;
}

I tried creating a function but I was not able to make it work, I'm still quite new at this.

Trax
  • 1,445
  • 5
  • 19
  • 39

3 Answers3

3

The most elegant way would be to use .every

The every() method tests whether all elements in the array pass the test implemented by the provided function.

if (array1.every(function(e,i){ return e>=array2[i];})) {
    do something;
}
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0
var isGreater = true;
for (var i = 0; i < array1.length; i++)
{
    if (array1[i] < array2[i])
    {
        isGreater = false;
        break;
    }
}

if (isGreater)
{
    //do something
}

You loop your first array and replace the numbers by the looping variable (i)

Shryme
  • 1,572
  • 1
  • 14
  • 22
  • 1
    This doesn't answer the question, which is that *all* elements of of the first are greater than the second, not *some*. – Joe Dec 13 '13 at 14:57
  • looking at his example, he was doing arr1[0] vs arr2[0], arr1[1] vs arr2[1], that's what my for loop is doing, he never asked how to check everything with everything – Shryme Dec 13 '13 at 14:59
  • I disagree. Look at his logic, it's `&&`ing all the conditions. – Joe Dec 13 '13 at 15:00
0

This will return true if all elements of a are greater than all elements of b. It will return as early as possible rather than having to compare all of the elements.

function compare(a, b) {
  for (i = 0; i < a.length; i++) {
      if (a[i] < b[i]) { return false;}
  }
  return true
 }
Joe
  • 46,419
  • 33
  • 155
  • 245