views:

76

answers:

3

I have an array of objects that contains a key value with true or false. These values start as false but switch to true on completion of their work. I was looking to determine when all the values had completed i.e. all switched to true. Is there a deviation(logic below) on a while loop with a test if statement that may solve this.

basicarray = [{"value" : false}, {"value" : false},
              {"value" : false}, {"value" : false},
              {"value" : false}  ];

non working logic


totalcount = 0;

while(totalcount < basicarray.length )
{
  for(a=0 ; a < basicarray.length; a++)
  {
    if(basicarray[a].value = true)
    {
      totalcount = totalcount + 1;
    }
  }
}
alert("all true");
+1  A: 

Use == in place of = :

if(basicarray[a].value == true)  // Notice the ==
{
   totalcount++;    // this better than totalcount = totalcount + 1
}

Or

if(basicarray[a].value)
{
   totalcount++
}
fastcodejava
Better to use `===` if you know the type.
rahul
You've missed the bigger error of infinite recursion if an instance of `basicarray[a].value != true`
Justin Johnson
@Justin - Where do you see recursion?
fastcodejava
The OP has `while(totalcount < basicarray.length ) { for(a=0 ; a < basicarray.length; a++) { ... } }` If `totalcount` doesn't get incremented inside for every element of `basicaarray`, the `while` loop will never exit.
Justin Johnson
Oh missed that completely. Your soln is neat.
fastcodejava
A: 

This will count the array elements at start and then subtract from the counter when an element is true. Once the counter is zero all elements should be true.

  var basicarray = [{"value" : true}, {"value" : true},
                {"value" : true}, {"value" : true},
                {"value" : true}  ];

  var c = basicarray.length;
  for(var i = 0; i < basicarray.length; i++) {
    if(basicarray[i].value) c--;
  }

  if(c == 0) {
    alert('All True');
  } 
Camsoft
You should use a normal `for` loop when iterating over arrays and `for..in` when iterating over object properties. Also, regardless of convention, you should always program defensively when using a `for..in` loop (e.g., you should always check the `hasOwnProperty` method).
Justin Johnson
Yes you're absolutely correct. Not sure why I used `for..in` statement. I've now corrected this.
Camsoft
-1 removed ----
Justin Johnson
+1  A: 

You're basically just doing a each from the functional paradigm. The following is equivalent:

var result = true;

for ( var i=0, l=basicarray.length; i<l; i++ ) {
    result = basicarray[i].value;

    // If result is ever false, there's no point in continuing
    if ( !result ) { break; }
}

console.log(result);
Justin Johnson
Why do `result = result `? Just `result = basicarray[i].value;` is okay.
fastcodejava
You're right. I originally had just that before I added the break, which makes it superfluous.
Justin Johnson