Return an array of the number smaller than n


Posted by Christy on 2022-04-19

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

Answer:

function findAllSmall(arr, n) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      result.push(arr[i]);
    }
  }
  return result;
}

console.log(findAllSmall([1, 2, 3], 10)); // [1, 2, 3]
console.log(findAllSmall([1, 2, 3], 2)); // [1]
console.log(findAllSmall([1, 3, 5, 4, 2], 4)); // [1, 3, 2]

Reflection:

Beware of return in a function, I wrote below at first beginning, it will end the whole function.

function findAllSmall(arr, n) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      return console.log(result.push(arr[i]));
    }
  }
}

findAllSmall([1, 2, 3], 10);

According to the question, below is better

function findAllSmall(arr, n) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < n) {
      result.push(arr[i]);
    }
  }
  return result;
}

The other answers:

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









Related Posts

關於 CSS 最 Confusing 的位置以及顯示方式

關於 CSS 最 Confusing 的位置以及顯示方式

Finite State Machine (FSM) 介紹

Finite State Machine (FSM) 介紹

npm and eslint

npm and eslint


Comments