Context
As JavaScript developers, we are constantly working with arrays and as time passed you may have encountered a situation where you needed to compare two arrays and find the difference between them.
In this article, we will explore a code snippet in native javascript that does just that, using only native methods reduce(), filter(), sort() and includes(). So, let's dive in and learn how to find the difference between two arrays in just one line (just kidding otherwise this oneliner would be prettry much unreadable haha).
Usage
diffBetweenArrays([
[1, 2, 3],
[1, 2],
]); // [3]
diffBetweenArrays([
[1, 2, 3],
[1, 2, 3],
]); // []
// ✅ Order doesn't matter
diffBetweenArrays([
[1, 2, 3, 4, 5],
[5, 2, 10],
]); // [1, 3, 4]
diffBetweenArrays([
[5, 2, 10],
[1, 2, 3, 4, 5],
]); // [1, 3, 4]
// ❌ Avoid more than 2D arrays
diffBetweenArrays([[1, 2, 3], [1, 2], [2]]);
// [3]
How does it work?
The diffBetweenArrays
takes a 2D array (more would have unexpected result) as its only argument then the function works in a few simple steps:
- First we sort our 2D array by array length with sort() to make sure that the longuest array is always first so that the order at which we provide them doesn't matter.
- The reduce() method is used to iterate over each provided arrays.
- For each iteration it compares the next_array with the result obtained from the previous iteration (this is why is returns unexpected results when you provide more than 2D array as parameter), if none it's initialized as the first array using the filter() method creating a new array with only the values that satisfy a given condition in our case the condition is provided by:
- The includes() method that checks if any value from the previous iteration is not present in the next_array.
- Lastly the reduce() method passes the resulting array to the next iteration until all arrays have been compared.
And tada 🎉
diffBetweenArrays([
["George", "Saint", "Pierre"],
["Saint", "Pierre"],
]);
// ['Conor']
Note: We could extend this function to match objects aswell with any comparison you'd like, for the sake of the example let's compare all the properties of the object by first converting it to a string like this:
const diffBetweenArrayOfObjects = (arrays) => {
return arrays
.sort((current, next) => (current.length > next.length ? -1 : 0))
.reduce((current_array, next_array) => {
return current_array.filter((currentObj) => {
return next_array.some((nextObj) => {
return JSON.stringify(currentObj) !== JSON.stringify(nextObj);
});
});
});
};
diffBetweenArrayOfObjects([
[
{ id: 1, name: "George" },
{ id: 2, name: "George Saint-Pierre" },
],
[{ id: 1, name: "George" }],
]);
// [{ id: 2, name: "George Saint-Pierre"" }]
Conclusion
The diffBetweenArrays function is a very useful snippet to return the difference between a 2D provided array, as a single array containing only values that are present in the first array but not in the second one.
Keep the good work! 🧠
Top comments (0)