Filtering out primes from an array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in the following array of numbers,

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

and returns a new filtered array that does not contain any prime number.

Example

Following is the code −

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));

Output

Following is the output in the console −

[
   34, 56, 56,  4, 343,
   68, 56, 34, 87,   8,
   45, 34
]
raja
Published on 18-Sep-2020 12:56:21
Advertisements