Skip to content

Instantly share code, notes, and snippets.

@bsdahl
Created October 14, 2020 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsdahl/fb7589c059d25dc17d2aa37abd93702e to your computer and use it in GitHub Desktop.
Save bsdahl/fb7589c059d25dc17d2aa37abd93702e to your computer and use it in GitHub Desktop.
Function to determine if intersecting keys are equal
export function areIntersectingKeysEqual(...objects) {
return objects
.map((object) => Object.keys(object))
.sort((a, b) => a.length - b.length)
.reduce((a, b) => a.filter((key) => b.includes(key)))
.every((key) => objects.every((object) => object[key] === objects[0][key]));
}
@bsdahl
Copy link
Author

bsdahl commented Oct 14, 2020

Let me explain how it works.

At a high level, first we find the intersecting keys, then we determine if all intersecting keys are equal.

  1. Map all objects, returning an array of key arrays.
  2. Sort the lists according to length ascending (this is an optimization, shortest key list is filtered first)
  3. Reduce our lists of keys, filtering them by the condition that the next array includes that key. This is how we find intersecting keys.
  4. Now that we have a list of intersecting keys, we can determine if the keys are equal. For every key, check that the value in every object is equal.
  5. Finally, return the resulting boolean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment