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
Remove elements from array using JavaScript filter - 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 to get the below output ?
const output = [7, 6, 3, 6, 3];
Method 1: Using filter() with indexOf()
The filter() method creates a new array with elements that pass a test. We use indexOf() to check if an element exists in the second array.
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));
[ 7, 6, 3, 6, 3 ]
Method 2: Using filter() with includes()
A more modern approach uses includes() method, which is more readable than indexOf().
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];
const arr2 = [4, 56, 23];
const filterArray = (arr1, arr2) => {
return arr1.filter(el => !arr2.includes(el));
};
console.log(filterArray(arr1, arr2));
[ 7, 6, 3, 6, 3 ]
Method 3: Using Set for Better Performance
For larger arrays, converting the second array to a Set improves performance since Set.has() is faster than Array.includes().
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];
const arr2 = [4, 56, 23];
const filterArray = (arr1, arr2) => {
const excludeSet = new Set(arr2);
return arr1.filter(el => !excludeSet.has(el));
};
console.log(filterArray(arr1, arr2));
[ 7, 6, 3, 6, 3 ]
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
indexOf() |
Good | Slower for large arrays | Small to medium arrays |
includes() |
Excellent | Slower for large arrays | Small to medium arrays |
Set |
Good | Fastest | Large arrays |
Conclusion
Use filter() with includes() for readability in most cases. For performance-critical applications with large arrays, prefer the Set approach.
