Cyril_n
Cyril_n

Reputation: 39

Javascript : test values in a 2D array

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*
    }
}

Upvotes: 0

Views: 494

Answers (3)

SergeyS
SergeyS

Reputation: 3553

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.
}

Upvotes: 0

Niles Tanner
Niles Tanner

Reputation: 4021

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*
}

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122047

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');

Upvotes: 4

Related Questions