countSheeps.js (8kyu 09)

Codewars 알고리즘 풀이


Problem

  • We need a function that counts the number of sheep present in the array.
    • 양(Sheep)의 수를 세는 함수를 작성한다.
    • true가 __있음(present)__을 의미한다.


Array of Sheep

const arr = [
  true, true, true, true,
  true, false, true, false,
  false, false, false, false
  false, true, true, false
];


Solution 01

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

countSheeps(arr);  // 8


Solution 02

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

countSheeps(arr);  // 8

filter() 메소드

테스트를 통과한 배열의 각 값을 모아, 새 배열로 반환한다.