0

How can I test the values of a 2D array ?

I have a 2D array that looks like this :

array: [
["A", 24, 5],
["B", 135, 5],
["C", 2124, 5]
]

What I need is to execute a function if all the values in position 2 : array[i][2] are equal to 5.

for (i = 0; i < array.length; i++){
    if (that.ptLiaison[i][2]=="5"){ //need to check all the instances of i at once
       *execute function*
    }
}
0

3 Answers 3

4

You can use every() method and return true/false

var array = [
  ["A", 24, 5],
  ["B", 135, 5],
  ["C", 2124, 5]
];

var result = array.every(function(arr) {
  return arr[2] == 5;
});

if(result) console.log('Run function');

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

Comments

0

You could use a a .every()

   if(that.ptLiaison.every(function(row){
      return row[2] == "5";
    })){

    }

This loops through and check that each iteration is true, and if they all are the entire operation returns true.

You could also use a more robust function:

var checkAllRows = function(array,index,value){
  return array.every(function(row){
    return row[index] == value;
  });
}

if(checkAllRows(that.ptLiaison,2,"5")){
  *do something*
}

Comments

0

There are several ways to do this. One of the ways is the following logic: if we want execute function when all elements equal 5, then it means if at least one element is not 5 we should not execute function. Code below:

var needExecuteFunction = true;
for (i = 0; i < array.length; i++){
    if (that.ptLiaison[i][2] != "5"){
       needExecuteFunction = false;
       break;
    }
}

if(needExecuteFunction){
    // execute it.
}

Comments

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.