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:

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 b:

Symmetric difference between two arrays

Another interesting problem is figuring out how to calculate the symmetric difference between two arrays in JavaScript. Basically I want to find all the elements that belong to one array but not the other.

There are two posts, from some time ago, that were useful to me:

I can find them by running two filters in sequence and then joining the arrays with the Array.prototype.concat() method or with the spread operator:

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 filter method:

Said in words, they are all the elements of a present in b.

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:

In some situations we want to avoid having repeated values. In this case it is better to use a Set: it is a JavaScript object that only collects different values, preventing us from creating duplicates.

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.