Often on a day to day as a developer is very common to work with arrays, I’d say is one of the most used data structures and there’s a need to learn how to manipulate them.
In this post, I’ll be explaning how to find the differences between two arrays of objects (this can be done with any array tho). So, let’s get into the code, let’s assume we have the next two arrays:
const array1 = [
{ id: 1, country: "USA" },
{ id: 2, country: "Canada" },
];
const array2 = [{ id: 1, country: "Canada" }];
const getDiff = (arr1, arr2) =>
arr1.filter((obj1) => !arr2.some((obj2) => obj1.id === obj2.id));
In this code, we have two arrays of objects, one of them with two elements and the second one with only one element on it. We create a function (the getDiff
function) that performs a filter and a some operation on the arrays. So:
- The
filter
iterates thru the first array. - And on each iteration we execute a
some
function in order to know if the current object (result from the filter function) is not contained in the second array.
And that’s it, as simply as that, but….(yes, there should be a but, otherwise it would be so easy) this is a partial solution. If you test this with the first array with only one element and the second array with two elements this solution will trhow an empty array. So, this will be your homework, and as a hint, you’ll may be need to use the spread operator.
Conclusion
When working as a developer is always good to know how to work with data structures, the arrays are the most common data structure you’ll find when working as a programmer, so, get to know your tools (filter
, some
, map
, etc.), practice in platforms like HackerRank and you’ll success on any task that has to do with arrays.