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
Selected Reading
How to get the difference between two arrays in JavaScript?
To get the difference between two arrays in JavaScript, you can find elements that exist in one array but not in both. This is commonly called the symmetric difference. There are several approaches to achieve this.
Using filter() and includes() (Recommended)
<html>
<head>
<title>Array Difference</title>
</head>
<body>
<script>
function arrayDifference(arr1, arr2) {
// Elements in arr1 but not in arr2
const diff1 = arr1.filter(item => !arr2.includes(item));
// Elements in arr2 but not in arr1
const diff2 = arr2.filter(item => !arr1.includes(item));
// Combine both differences
return [...diff1, ...diff2];
}
const result = arrayDifference([50, 40, 90], [70, 50, 99, 40, 90]);
document.write("Difference: " + result.join(", "));
</script>
</body>
</html>
Difference: 70, 99
Using Set for Better Performance
<html>
<body>
<script>
function arrayDifferenceSet(arr1, arr2) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const diff = [...arr1.filter(x => !set2.has(x)),
...arr2.filter(x => !set1.has(x))];
return [...new Set(diff)]; // Remove duplicates
}
const arrays1 = [1, 2, 3, 4];
const arrays2 = [3, 4, 5, 6];
const result = arrayDifferenceSet(arrays1, arrays2);
document.write("Array 1: [" + arrays1.join(", ") + "]<br>");
document.write("Array 2: [" + arrays2.join(", ") + "]<br>");
document.write("Difference: [" + result.join(", ") + "]");
</script>
</body>
</html>
Array 1: [1, 2, 3, 4] Array 2: [3, 4, 5, 6] Difference: [1, 2, 5, 6]
One-Way Difference
To find elements in the first array that are not in the second array:
<html>
<body>
<script>
function oneWayDifference(arr1, arr2) {
return arr1.filter(item => !arr2.includes(item));
}
const colors1 = ["red", "blue", "green"];
const colors2 = ["blue", "yellow", "green"];
const result = oneWayDifference(colors1, colors2);
document.write("Elements in first array but not in second: [" + result.join(", ") + "]");
</script>
</body>
</html>
Elements in first array but not in second: [red]
Comparison of Methods
| Method | Performance | Handles Duplicates | Best For |
|---|---|---|---|
| filter() + includes() | Good for small arrays | Keeps duplicates | Simple cases |
| Set-based approach | Better for large arrays | Removes duplicates | Large datasets |
Conclusion
Use filter() with includes() for simple array differences. For better performance with large arrays, use the Set-based approach which also handles duplicates efficiently.
Advertisements
