
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Elements from Array Using JavaScript Filter
Suppose, we have two arrays of literals like these −
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4]; const arr2 = [4, 56, 23];
We are required to write a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array.
And then return the filtered array to get the below output −
const output = [7, 6, 3, 6, 3];
Example
Following is the code −
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4]; const arr2 = [4, 56, 23]; const filterArray = (arr1, arr2) => { const filtered = arr1.filter(el => { return arr2.indexOf(el) === -1; }); return filtered; }; console.log(filterArray(arr1, arr2));
Output
This will produce the following output in console −
[ 7, 6, 3, 6, 3 ]
Advertisements