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

【JS幼幼班】Step.04 基本語法:變數

【JS幼幼班】Step.04 基本語法:變數

[Day 02] - Vault 的啟動及 Unseal 概念

[Day 02] - Vault 的啟動及 Unseal 概念

為什麼你不應該自己組 query string

為什麼你不應該自己組 query string


Comments