Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to check if every value in a nested array is true or false?

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?

like image 394
anoop chandran Avatar asked Mar 24 '20 19:03

anoop chandran


3 Answers

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));
like image 141
Maheer Ali Avatar answered Oct 22 '22 08:10

Maheer Ali


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);
like image 26
Nina Scholz Avatar answered Oct 22 '22 06:10

Nina Scholz


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);
like image 27
mickl Avatar answered Oct 22 '22 07:10

mickl