Home > Net >  Counting sheeps
Counting sheeps

Time:12-14

So i'm trying to use the push method to solve the couting sheeps problem. Basically in this problem i need to count how many "true" there is in a given array. The array itself is

[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]

And i want to understand why the push method, that seem to REMOVE the last index of the array and RETURN it does not work.

function countSheeps(arrayOfSheep) {

  let a = arrayOfSheep;
  let b = 0;
  let answer = 0;
 
  
    for(let i = 0; i < a.length; i  ){
      b = a.push();
        if(b === true){
          answer  = 1;
}
}
  return answer;
}

In my thinking, each time the for loop goes, the length of array a are reduced by one. So in the final loop the array a is [0] and the if makes the answer variable to be equal to 17, but it always return 0.

CodePudding user response:

I think your approach is overly complex. If I wanted to count how many items in a list match some criteria, I would just look at each item and increment a counter if it matches until I was done with the entire array.

function countTrue(arr) {
  // accumulator variable, at the end of each iteration
  // of the loop, `result` will be gauranteed to have the
  // total number of `true` elements seen so far
  let result = 0;
  // iterate over the entire array
  for (const item of arr) {
    if (item === true) {
      // this item is true, increment our accumulator
      result  ;
    }
  }
  // return our accumulated result, zero or otherwise.
  return result;
}

CodePudding user response:

You don't need to push any new value to simply count unique items in an array.

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

var total = 0;
array.forEach(function (item){
  if(item){
    total  ;
  }
});
console.log(total);

CodePudding user response:

You could just add the boolean values.

const
    array = [true, true, true, false, true, true, true, true, true, false, true, false, true, false, false, true, true, true, true, true, false, false, true, true],
    result = array.reduce((a, b) => a   b, 0);

console.log(result);

  • Related