const diffBetweenArrays = (arrays) => {
return arrays
.sort((current, next) => (current.length > next.length ? -1 : 0))
.reduce((acc, next_array) => {
return acc.filter((value) => {
return !next_array.includes(value);
});
});
};
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).
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]
The diffBetweenArrays
takes a 2D array (more would have unexpected result) as its only argument then the function works in a few simple steps:
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) => {
// Compare objects based on their properties
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"" }]
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! 🧠
Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.
Feel free to me through this learning journey by providing any feedback and if you wanna support me: