

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Filter array based on another array in JavaScript
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.
Therefore, the output should look like −
const output = [7, 6, 3, 6, 3];
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
[ 7, 6, 3, 6, 3 ]
- Related Questions & Answers
- Filter an array containing objects based on another array containing objects in JavaScript
- Sorting Array based on another array JavaScript
- Sort array based on another array in JavaScript
- Modify an array based on another array JavaScript
- Filter an object based on an array JavaScript
- Filter one array with another array - JavaScript
- Sort object array based on another array of keys - JavaScript
- Filter JavaScript array of objects with another array
- Get range of months from array based on another array JavaScript
- JavaScript in filter an associative array with another array
- Order an array of words based on another array of words JavaScript
- Creating an array of objects based on another array of objects JavaScript
- How to filter object array based on attributes in jQuery?
- How to filter documents based on an array in MongoDB?
- C# Program to filter array elements based on a predicate
Advertisements