6

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?

3 Answers 3

9

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));
Sign up to request clarification or add additional context in comments.

1 Comment

beat by milliseconds, bravo
6

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);

1 Comment

I decided to use this solution. I don't need to check every value in my case. My bad, I should have mentioned in the description. Good one!
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.