I have a nested array like this.
var arr = [[false,false,false,false],[false,false,false,false],[false,false,false,false],[false,false,false,false]]
I want to check if every value is false. I could think of one way of doing this.
let sum = 0;
arr.forEach((row, i) => {
row.forEach((col, j) => {
sum = sum +arr[i][j]
});
});
if(sum === 0){
console.log("all values false")
}
This works. But I'm curious if there is a better way? to check if all values are true or false?
You can use nested every()
var arr = [[false,false,false,false],[false,false,false,false],[false,false,false,false],[false,false,false,false]]
const res = arr.every(x => x.every(a => a === false));
console.log(res)
To make the code a little more cleaner you can first flat()
and then use every()
var arr = [[false,false,false,false],[false,false,false,false],[false,false,false,false],[false,false,false,false]]
const res = arr.flat().every(x => x === false)
console.log(res)
I am considering you want to check of only false
. If you want to check for all the falsy values(null, undefined
etc). You can use !
instead of comparison with false
const res = arr.every(x => x.every(a => !a));
You could take two nested Array#some
, because if you found one true
value the iteration stops. Then take the negated value.
var array = [[false, false, false, false], [false, false, false, false], [false, false, false, false], [false, false, false, false]],
result = !array.some(a => a.some(Boolean));
console.log(result);
You can use .array.every()
method:
var arr = [[false,false,false,false],[false,false,false,false],[false,false,false,false],[false,false,false,false]]
let result = arr.every(x => x.every(y => y === false));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With