Public Solving: Find the missing presents
permalinkOh no, some of the presents have gone missing, and Santa asked us to quickly write a program to find the missing ones.
Luckily for us, the elves are super organized and have a list of all presents there would be.
They also provided us a manifest with all the presents id's that should be in the current sack of Santa.
You can find the original puzzle here.
Thinking about a solution permalink
This is quite a quick assignment, by the looks of it.
We basically start with three arrays:
- The full item array (id + name of each present) - all items
- Manifest array (id) - items that should be in the sack
- Sack array (id) - items in the sack
I want to break this up into two elements to make things readable and easy to grasp.
- Find the missing items by comparing the manifest and the sack.
- Return the complete item object by comparing the items with the missing array we just created.
Alright, let's get cracking on this puzzle.
Find missing elements in two arrays in JavaScript permalink
The first part compares the two arrays (manifest and sack). They contain ID's so we can use the filter
method to quickly filter out the missing one.
A present would be missing if it exists in the manifest array but not in the sack array.
const missing = manifest.filter((el) => !sack.includes(el));
And then, we can use this array to filter the items array to output the id and name of that present.
return items.filter((el) => missing.includes(el.id));
And we can even write this as a one-liner for those interested.
export const findMissing = (manifest, sack) => {
return items.filter((item) =>
manifest.filter((el) => !sack.includes(el)).includes(item.id)
);
};
Let's try out the test to see if it worked.
Let me know in the comments what you would do differently.
Thank you for reading, and let's connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter