[codewars] Counting sheep...

KJA·2022년 8월 18일
0

https://www.codewars.com/kata/54edbc7200b811e956000556


Description

Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

Example

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

The correct answer would be 17.

Hint: Don't forget to check for bad values like null/undefined

문제 해결

function countSheeps(arrayOfSheep) {
  let cnt = 0;
  for (let i = 0; i < arrayOfSheep.length; i++) {
    if(arrayOfSheep[i]) cnt++;
  }
  return cnt;
}

다른 풀이

filter 사용

function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter(Boolean).length;
}

0개의 댓글