JavaScript如何从数组中滤除素数

2023年11月23日10:56:35

我们需要编写一个JavaScript函数,该函数接受以下数字数组,

const arr = [34, 56, 3, 56, 4, 343, 68, 56, 34, 87, 8, 45, 34];

并返回一个不包含任何质数的新过滤数组。

示例

以下是代码-

const arr = [34, 56, 3, 56, 4, 343, 68, 56, 34, 87, 8, 45, 34];
const isPrime = n => {
   if (n===1){
   return false;
   }else if(n === 2){
      return true;
   }else{
      for(let x = 2; x < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const filterPrime = arr => {
   const filtered = arr.filter(el => !isPrime(el));
   return filtered;
};
console.log(filterPrime(arr));

输出结果

以下是控制台中的输出-

[
   34, 56, 56,  4, 343,
   68, 56, 34, 87,   8,
   45, 34
]

  • 更新时间:2023年11月23日10:56:35 ,共 613 字。