Return the count of the number smaller than n


Posted by Christy on 2022-04-19

Description: Write a function named findSmallCount that accepts an array and a number n, returns the count of the number smaller than n.

function findSmallCount(arr, n) {

}

findSmallCount([1, 2, 3], 2) // 1
findSmallCount([1, 2, 3, 4, 5], 0) // 0
findSmallCount([1, 2, 3, 4], 100) // 4
function findSmallCount(arr, n) {
  let counter = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      counter += 1;
    }
  }
  return counter;
}

console.log(findSmallCount([1, 2, 3], 2)); // 1
console.log(findSmallCount([1, 2, 3, 4, 5], 0)); // 0
console.log(findSmallCount([1, 2, 3, 4], 100)); // 4

Reflection:

Beware of what the output is, here's the count.

The other answers:

function findSmallCount(arr, n) {
  let i = 0;
  let counter = 0;
  do {
    if (arr[i] < n) {
      counter++;
    }
    i++;
  } while (i < arr.length);
  return counter;
}
function findSmallCount(arr, n) {
  let i = 0;
  let counter = 0;
  while (i < arr.length) {
    if (arr[i] < n) {
      counter++;
    }
    i++;
  }
  return counter;
}









Related Posts

[ JavaScript 02 ] 變數

[ JavaScript 02 ] 變數

HTTP Status Code

HTTP Status Code

2023 D4SG 成果發表會心得

2023 D4SG 成果發表會心得


Comments