Subscribe

Public Solving: Find the missing presents

โœ๏ธ

Comparing array differences in JavaScript

3 Jan, 2022 ยท 2 min read

Oh 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

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.

  1. Find the missing items by comparing the manifest and the sack.
  2. 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

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.

Padding the tests

Let me know in the comments what you would do differently.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Public Solving: Caesar decipher in JavaScript

2 Jan, 2022 ยท 4 min read

Public Solving: Caesar decipher in JavaScript

Public Solving: Creating a song with JavaScript

31 Dec, 2021 ยท 4 min read

Public Solving: Creating a song with JavaScript

Join 1509 devs and subscribe to my newsletter