I have simple JavaScript question.
I have an array (xyz) of 9 objects (Cell), each with 2 properties (e,v).
Is there any easy way to check if all the values of one of the properties are false?
Something like:
var myArray = xyz[];
if(all myArray.e==false){
do this;
}
Thanks :D
Array[9]
0:Cell
e:false
v:"x"
1:Cell
2:Cell
3:Cell
4:Cell
...etc
You can use JavaScript Array every() Method
var myArray = [xyz];
if (myArray.every(obj => !obj.e)) {
do this;
}
You could do this with the reduce
function.
Try:
const areAllFalse = !myArray.reduce((prev, cur) => prev || cur, false)
Check out the MDN docs for reduce
for more info on how it works.
You should do
let areAllFalse = true;
for (let obj in myArray){
if (e.v) {
areAllFalse = false;
break;
}
}
if (areAllFalse){
// Do stuff
}
Basically:
areAllFalse
) to true (you are assuming that all the elements will be false) areAllFalse
is true, every element in the array is false, so you can execute your code This will work in every programming language (with the obvious syntax changes)
I hope I helped you :)
There's a few different ways you could approach this. One way would be by using every
. ( MDN Docs )
function myTest(thisItem) {
return !thisItem.e;
}
var myArray = [
{e: false, v: 111},
{e: false, v: 222},
{e: false, v: 333}
];
var output = myArray.every(myTest);
console.log(output);
// expected output: true
You can use array#every
with to check for your condition to be true for all the objects in your array. Use Object#keys
to iterate over keys in an object and check for false value using array#some
.
var arr = [{e:false, v:'x'}, {e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'}], result = arr.every(o => Object.keys(o).some(k => !o[k])); console.log(result);
To check for e
property in your object, you should first check if e
key exists in the object then check if its value is false.
var arr = [{e:false, v:'x'}, {e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'},{e:false, v:'x'}], result = arr.every(o => 'e' in o && !oe); console.log(result);
You have multiple options to do that, like
But for short answer I think you can use findIndex that will return index if it matches condition: Example :
if(xyz.findIndex(k => k.e== false) > -1){
console.log("it contains false value also");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.