I have a multidimensional array of bools, with each element set to true:
var boolarray= $.extend(true, [], board);
board is a 3x3 multidimensional array of strings. boolarray is simply a deep copy of this.
for (var i=0; i < boolarray.length; i++) {
boolarray[i]
for (var j=0; j < boolarray[i].length; j++) {
boolarray[i][j] = true;
};
};
This gives me:
boolarray = [true,true,true,true,true,true,true,true,true]
I want to check if all elements are true and return if this is the case. However my method below does not work.
if (boolarray == true)
{
console.log("all elements in boolarray are true, return true ")
return true;
}
else
{
console.log("not all elements in boolarray are true, return false")
return false;
}
Any ideas of how I should check if boolarray is all true?
To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements.
Checking array elements using the for loop First, initialize the result variable to true . Second, iterate over the elements of the numbers array and check whether each element is less than or equal zero. If it is the case, set the result variable to false and terminate the loop immediately using the break statement.
size = function(obj) { var size = 0, key; for (key in obj) { if (obj. hasOwnProperty(key)) size++; } return size; }; var size = Object. size(arr); if (size > 0) { alert("NOT empty!") } else { alert("empty...") }
Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.
Use .every()
...
var boolarray = [true,true,true,true,true,true,true,true,true];
boolarray.every(Boolean);
DEMO: http://jsfiddle.net/gFX7X/
If the only purpose of the first loop was to create the second, then you could skip it and do this...
var boolarray = [[true, true, true],
[true, true, true],
[true, true, true]];
boolarray.every(function(arr) {
return arr.every(Boolean)
});
DEMO: http://jsfiddle.net/gFX7X/1/
Or a slightly shorter version of the previous one:
boolarray.every(Function.call.bind(Boolean, null))
As an alternative to using a boolean array why not use a simple Hexidecimal number to store your board (and then use bit manipulation to change/test) i.e.
000 000 001
==
1decimal
111 111 111
==
511 (256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Setting a board position true or false would then become a bit manipulation and testing would become as simple as parseInt = 511...
see bit manipulation in javascript
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