Skip to content

Instantly share code, notes, and snippets.

@bsdahl
Last active October 13, 2020 23:25
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/2175aaf2885f0a4bbc00ade99a5f5365 to your computer and use it in GitHub Desktop.
Save bsdahl/2175aaf2885f0a4bbc00ade99a5f5365 to your computer and use it in GitHub Desktop.
Function that will find intersecting keys for n number of object arguments.
export function intersectingKeys(...objects) {
return objects
.map((object) => Object.keys(object))
.sort((a, b) => a.length - b.length)
.reduce((a, b) => a.filter((key) => b.includes(key)));
}
@bsdahl
Copy link
Author

bsdahl commented Oct 13, 2020

How do you find intersecting keys of n number of objects?

  1. First we build an array where each element is the set of keys of each object.
  2. Then we sort the lists of keys from smallest to largest, this is for efficiency
  3. Then we reduce the set of keys, by comparing A set of keys to B set of keys, finding the intersecting of keys. Each iteration the previous result is compared to the next set.
  4. Finally return the resulting set of intersecting keys

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