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.

2
  • Refer this link with a similar Question posted <br> stackoverflow.com/questions/3432929/… Commented Dec 13, 2013 at 14:54
  • @DevendraLattu that question isn't at all similar Commented Dec 13, 2013 at 15:08

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 For the most elegant solution. I deleted my answer which was basically identical, but slower :) .
I tried this one but I'm getting a syntax error "missing ; before statement".
Yeah, I'm missing a } here, one sec... Fixed. @user3099816
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
 }

Comments

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)

3 Comments

This doesn't answer the question, which is that all elements of of the first are greater than the second, not some.
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
I disagree. Look at his logic, it's &&ing all the conditions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.