9

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?

5
  • just iterate all rows and columns and if any element = false return false else return true... If you wanted to make it a function that was easy to call then use prototype on the board class which would expose an isAllTrue method Commented Apr 10, 2012 at 22:07
  • @Paul, and if the first cell is true, you are returning true? you need to search the entire array, and then return true. Commented Apr 10, 2012 at 22:08
  • no if all iteraations of the loop have failed return true (all are true) Commented Apr 10, 2012 at 22:17
  • and see my bitwise alternative to all the Log(On) algorithms Commented Apr 10, 2012 at 22:17
  • Note that the line boolarray[i] (immediately after the for loop's opening {) doesn't do anything. Commented Apr 10, 2012 at 22:17

11 Answers 11

29

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

6 Comments

MDN's reference on .every() tells me it takes a function. How is it that passing Boolean works? It sure seems to :) I changed one of the values in the first example to false and sure enough it returned false. It also looks like the first argument passed to the callback is the value, rather than the array.
@jinglesthula: typeof Boolean === "function"; // true :-) The Boolean function, when not use as a constructor simply converts its first argument to a boolean and returns it. So in these examples, it's taking the true value, and returning true.
Note that, empty array will also cause it to return true, which is incorrect. [].every(Boolean); will yield true.
@codenamezero: That's true, but your claim that it's incorrect is subjective. There is no "correct" result. There's only what a person decides they want to get in that situation since both true and false are somewhat misleading. If you wanted false, you can do !!boolarray.length && boolarray.every(Boolean);
Yeah, the length check is needed. I'm just throwing this here so that people would know.
|
3

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

3 Comments

This is interesting I will look into this for future learning, thanks.
No problem - note that this method will require about as much coding but will be much faster (parseInt is optimised in the javascript engine, not Log(On) i.e. the bigger the array the longer it takes worst case and smaller memory footprint
Additonally this works for all instances where you would have to iterate the array to test i.e. 'are all values false' = parseInt == 0? and 'is any bit true' = parseInt > 0
1

You would need to loop through the array again to check all the values; in a very similar way to how you assigned them:

for (var i=0; i < boolarray.length; i++) {
    for (var j=0; j < boolarray[i].length; j++) {
        if (boolarray[i][j] == false) {
            return false;
        }
    };
}; 

return true;

Comments

1

Write a function that runs a loop on a given parameter (our 2d array), and checks each cell if true. If not, return false. After the loop, return true;

Comments

1
bool alltrue = true;
for (var i=0; i < boolarray.length; i++) {
              boolarray[i]
              for (var j=0; j < boolarray[i].length; j++) {
                if(boolarray[i][j] != true) {
                    alltrue = false;
                }
              };
            };     

Comments

1

ES5 notation example (simplified):

var foo = [ [true, true, true], [true, true], [true, true], [false, true], [true, true] ];

var boolarray = foo.every(function(level2, i) {
    return level2.every(function(bool) {
        return bool;
    });
});

This example exploits the fact that Array.prototype.every returns the result which returned from the loop function. As soon as a falsy value is returned, the iteration stops aswell.

If you need to stay compatible with old'ish browsers live IE6/7 you can just download one of the many ES5 shim librarys out there

Comments

1

your variable named boolArray is an array and as long as it is not null, the code you wrote will se it as true, to get what you want you need something like this:

var boolArrayValue = true; // valor final a usar es boolarray value
for(var i = 0;i<boolarray.length;i++){
    for(var a = 0;a<boolarray[i].length;a++){
        boolArrayValue = boolArrayValue && boolarray[i][a];
    }
}

Comments

1
for(var i in boolarray)
    if(!boolarray[i]) return false;

return true;

...this is based on your statement:

boolarray = [true,true,true,true,true,true,true,true,true]

Which is NOT a multi-dimensional array.

5 Comments

his loop indicates he stores 3 booleans in an object array which is a multi dimensional array [i][j]
@PaulSullivan - It's hard to know if the op's code is what it is, when he says "this is what it gives me" and indicates a flat array. I understand the loop, but the last bit of information (despite that) is that op's working with a 1-D array.
@PaulSullivan Are you sure? You're operating under the assumption that the code snippet is what's being used to create boolarray? Why, when the op explicitly states var boolarray= $.extend(true, [], board);? Where's the code to initialize board? I on the other hand am assuming that one way or another, the op has what he has after code execution: boolarray = [true,true,true,true,true,true,true,true,true]
but the iteration of the elements indicates it is a multi boolarray[i][j] = true;... I agree this is a moot point he could easily use a single dim array and just mulitplex the array.
@PaulSullivan Yeah. I guess my point is - until we see where/how board is created, we can't be sure of what the data is. And in light of that, I chose to base my answer on what the op said his data contains after his logic has been applied.
1
boolarray = [true,true,true,true,true,true,true,true,true];
Array.prototype.isFalse=function(){
    for(var i=0;i<this.length;i++)
    {
        if(this[i]!=true) return false;
    }
    return true;
};
alert(boolarray.isFalse());​

A fiddle here.

1 Comment

prototyping Array is a grey area (I've read quite a lot of material that doesn't recommend due to many things (broken associative array behaviour and other broken ECMA stuff... handle Array.prototype with care
0

A recursive version that checks nested arrays of arbitrary depth:

function deepEvery(arr, fn, _this) {
    return (function iterate(arr, i) {
        var len = arr && arr.length;
        if (!len || i >= len) {
            return false;
        }
        var first = arr[i] && typeof arr[i].splice === "function" 
            ? iterate(arr[i], 0) 
            : fn.call(_this || this, arr[i], i);
        i += 1;
        return !!first && (i >= len || iterate(arr, i));
    })(arr, 0);
}

Usage:

deepEvery([[true, true, true], 
           [true, true, true], 
           [true, true, true]], function(el, i) {
    return el;
});

Note that this allows for any type of check in the callback. If the function you pass to deepEvery returns false for any element, then the overall result is false; otherwise, the result is true. Example:

deepEvery([4, true, [6, [5, "F"], 6]], function(el, i) {
    return typeof el === "number";
});

Comments

0

Using jQuery.grep() and jQuery.map():

var flattenedBoolarray = $.map(boolarray, function recurs(n) {
    return ($.isArray(n) ? $.map(n, recurs): n);
});

if ($.grep(flattenedBoolarray, function(e, i){return e}, true).length) {
    // In case if any isn't true
} else {
    // In case if all are true
}

DEMO: http://jsfiddle.net/tYSu6/

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.