Something went wrong at the North Pole. Santa Claus did a sample check: he discovered that some gifts are missing in the bags. Fortunately, everything is recorded and we can compare the various lists to find the differences. We can add the missing packages.
The Puzzle: Find The Missing Presents 🎁
I think Dev Advent Calendar problem 23 🎅 is the one with the shortest solution: literally 2 lines of code are enough to solve it:
The question is “how do I find elements that are in one array but not the other?”.
Find the differences between 2 arrays
To answer this question just combine two methods of arrays:
- Array.prototype.filter(), returns a new array containing all elements that pass a given test
- Array.prototype.includes(), returns the value
trueif the array contains a specified element
I can then derive this function:
The second part of the puzzle involves returning an array of objects taken from the array with the elements just found. I can change the function like this:
I can shorten the code by modifying the test passed to
filter. Another way to calculate the difference is to say that the element
x is included in
a but not in
Symmetric difference between two arrays
There are two posts, from some time ago, that were useful to me:
- Array intersection, difference, and union in ES6
Intersection of two arrays
Another common operation is to calculate the intersection of two arrays. In other words, how can we get a new array containing all the elements present at the same time in the two starting arrays?
Again with the
Said in words, they are all the elements of
a present in
Union of two arrays
The last operation is the union of two arrays. There are two ways of defining this operation. We can simply merge two arrays without caring for any duplicate values:
I can convert an array to a set just like this:
The reverse operation, converting a set to an array, is simple:
I can join two arrays without repeating the double values with this function:
Okay, maybe I went a little off topic from today’s exercise. But it was the right occasion for me to review the arrays.