- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filtering out primes from an array - JavaScript
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 ]
Advertisements