Javascript

Quiz - JS 배열내장 함수 문제

Starters 2020. 8. 23. 14:38

 

내가 만든 코드

function countBiggerThanTen(num){
  for(let i = 0; i < num.length; i++){
    if(num[i] <= 10){
      num.shift();
      i -= 1;
    }
  }
  return num.length;
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count);

 

정답 예시 1

function countBiggerThanTen(numbers) {
  let count = 0;
  numbers.forEach(n => {
    if (n > 10) {
      count++;
    }
  });
  return count;
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5

정답 예시 2

function countBiggerThanTen(numbers) {
  return numbers.filter(n => n > 10).length;
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5

정답 예시 3

function countBiggerThanTen(numbers) {
  return numbers.reduce((acc, current) => {
    if (current > 10) {
      return acc + 1;
    } else {
      return acc;
    }
  }, 0);
}

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5