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 動態效果 補

CSS 動態效果 補

關於 Fetch API

關於 Fetch API

[8] 進階資料型別 part3 - Set、Dict

[8] 進階資料型別 part3 - Set、Dict


Comments