Reputation: 297
When I want to detect if one element has a specific value, I do it like this:
For ( var i = 0 ; i < nOccCount ; i++ ) {
var V = i;
if (V == 'X') { break; }
}
Now I want to verify if all elements (i = 0; i < nOccCountare; i++)
are equal to 'X'
.
How can I do that?
Thank you.
Upvotes: 1
Views: 249
Reputation: 33726
You can use the function every
for doing that.
let allEqualToX = array.every(e => e === "X")
Upvotes: 2
Reputation: 7769
So i change the code as you need, Created one array:
var arr = [];
arr variable value is:
(7) ["x", "x", "x", "x", "x", "x", "x"]
created one variable to track, is any value not matched with desired character:
var allSame = true;
one for loop:
for(var i = 0; i < arr.length; i++){
if(arr[i] != 'x'){
allsame = false
}
}
var allSame = true;
var arr = ["x", "x", "x", "x", "x", "x", "x"]
for(var i = 0; i < arr.length; i++){
if(arr[i] != 'x'){
allsame = false
}
}
console.log(allSame);
alert("Are all value same :" + allSame);
Upvotes: 0
Reputation: 1673
There are many ways to do it (for arrays you can see Ele's suggestion in the comments).
For the general idea you presented in the question, you just need to add a boolean variable and change your condition to search for a not equal element like this:
var allEqual = true;
for (var i = 0; i < nOccCount; i++) {
var v = i;
if (v != 'X') {
allEqual = false;
break;
}
}
Because of the change !=
in the condition, allEqual
will be false if one or more elements are not equal to the value you are comparing to.
Upvotes: 0