Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Filtering out primes from an array - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns a new filtered array that does not contain any prime number.
Problem Statement
Given an array of numbers, we need to filter out all prime numbers and return only the composite and non-prime numbers.
const arr = [34, 56, 3, 56, 4, 343, 68, 56, 34, 87, 8, 45, 34];
Understanding Prime Numbers
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Numbers like 2, 3, 5, 7, 11 are prime numbers.
Solution
We'll create a helper function to check if a number is prime, then use the filter() method to exclude prime numbers from the array.
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 ]
How It Works
The isPrime() function checks if a number is prime by:
- Returning
falsefor 1 (not considered prime) - Returning
truefor 2 (the only even prime) - Testing divisibility from 2 to n-1 for other numbers
The filterPrime() function uses filter() with the negation of isPrime() to keep only non-prime numbers.
Optimized Version
For better performance with larger numbers, we can optimize the prime checking algorithm:
const arr = [34, 56, 3, 56, 4, 343, 68, 56, 34, 87, 8, 45, 34];
const isPrimeOptimized = n => {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) {
return false;
}
}
return true;
};
const filterPrimeOptimized = arr => {
return arr.filter(el => !isPrimeOptimized(el));
};
console.log(filterPrimeOptimized(arr));
[ 34, 56, 56, 4, 343, 68, 56, 34, 87, 8, 45, 34 ]
Key Points
- The optimized version only checks up to the square root of the number
- It skips even numbers after 2 and multiples of 3
- Uses the
filter()method with negation to exclude prime numbers - Both versions produce the same result but the optimized one is more efficient
Conclusion
Filtering out prime numbers requires a prime checking function combined with array filtering. The optimized approach significantly improves performance for larger datasets by reducing the number of divisibility tests needed.
