I have the following array:
var x = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
and I must check that the elements of the array are exactly in that order. I did the following function:
function chequearSiGano() {
for (i=0; i<x.length; i++){
if (x[0]=[1,2,3]){
return true;
}
else if (x[1]=[4,5,6]){
return true;
}
else if (x[2]=[7,8,9]){
return true;
}
else {
return false;
}
}
}
But I wanted to know if there is a more efficient way to do it so that I can apply it in the event that an element is added to the array in the future. Thank you!
Take into account that if your first condition meets then it will not enter the other cases, and that does not mean that it is exactly in that order as you request. So the logic would be wrong. Also you never use the variable that iterates in the for loop
In order to verify it you could do it this way using && :
Or the simplest way of all, compare the variable with the array:
If your matrix is always going to have 3 columns and n rows, you can first loop through the rows and see if each value of vector x[i] corresponds to the value it should have based on row x 3 and column + 1:
The first matrix is incorrect and the second is correct.
I add this other answer based on the sequence that starts from 1 :
this applies to various vectors such as :
Or whatever comes to your mind (as long as x[0][0]=1 as your example shows )
The idea is to check each position if it is greater by 1 than the previous position: