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
How to filter an array from all elements of another array – JavaScript?
In JavaScript, filtering an array to exclude elements present in another array is a common task. This involves removing all elements from the first array that match any element in the second array.
When storing multiple values in a single variable, arrays are used. Each element of an array has a numeric index that enables access to it. Arrays in JavaScript begin at index zero and can be modified using various methods.
Using filter() with includes() (Recommended)
The most straightforward approach combines filter() with includes() to exclude matching elements:
<!DOCTYPE html>
<html>
<body>
<script>
var array1 = [0, 7, 8, 6, 9, 3];
var array2 = [6, 8, 3];
var result = array1.filter(item => !array2.includes(item));
document.write("Original array1: " + array1);
document.write("<br>Array to exclude: " + array2);
document.write("<br>Filtered result: " + result);
</script>
</body>
</html>
Original array1: 0,7,8,6,9,3 Array to exclude: 6,8,3 Filtered result: 0,7,9
Using filter() with indexOf()
An alternative approach uses indexOf() to check if elements exist in the second array:
<!DOCTYPE html>
<html>
<body>
<script>
var array1 = [100, 110, 150, 180, 190, 175];
var array2 = [100, 150, 175];
var result = array1.filter(function(item) {
return array2.indexOf(item) === -1;
});
document.write("Filtered result: " + result);
</script>
</body>
</html>
Filtered result: 110,180,190
Using Set for Better Performance
For larger arrays, converting the exclusion array to a Set improves performance:
<!DOCTYPE html>
<html>
<body>
<script>
var array1 = [1, 2, 3, 4, 5, 6, 7, 8];
var array2 = [2, 4, 6, 8];
var excludeSet = new Set(array2);
var result = array1.filter(item => !excludeSet.has(item));
document.write("Numbers: " + array1);
document.write("<br>Exclude even: " + array2);
document.write("<br>Odd numbers: " + result);
</script>
</body>
</html>
Numbers: 1,2,3,4,5,6,7,8 Exclude even: 2,4,6,8 Odd numbers: 1,3,5,7
Comparison of Methods
| Method | Performance | Readability | Best For |
|---|---|---|---|
filter() + includes() |
Good | Excellent | Small to medium arrays |
filter() + indexOf() |
Good | Good | Older browser support |
filter() + Set |
Excellent | Good | Large arrays |
Key Points
- The
filter()method creates a new array without modifying the original -
includes()is the most readable approach for element checking - Use
Setfor better performance with large exclusion arrays - All methods preserve the original array order
Conclusion
The combination of filter() and includes() provides the clearest solution for filtering arrays. For performance-critical applications with large datasets, consider using Set-based filtering.
