Skip to content

Instantly share code, notes, and snippets.

@fimion
Forked from cfjedimaster/snippet.js
Last active June 27, 2024 23:09
Show Gist options
  • Save fimion/d05eb68b70b57a3f51f5a870de886acc to your computer and use it in GitHub Desktop.
Save fimion/d05eb68b70b57a3f51f5a870de886acc to your computer and use it in GitHub Desktop.
/**
*
* @param {string} key - the unique key on each object
* @param {Array} arrays - the arrays to be iterated over
* @returns an array of unique objects between all the passed arrays
*/
function getUniqueObjectsFromMultipleArrays(key, ...arrays){
// Make a place to store everything
const objectMapper = new Map();
// filter out anything not an array
const filteredArrays = arrays.filter((el)=>Array.isArray(el));
// Set up our values. uniqueSet will evenutally be a collection of unique ids.
let currentArray, uniqueSet;
// if we pop from arrays and nothing is left, this will be undefined, and will end.
while(currentArray = filteredArrays.pop()){
// Let's collect all the unique IDs in our current array.
const currentIds = new Set();
// loop over everything
currentArray.forEach((el)=>{
// our unique key
const id = el[key];
// add our id
currentIds.add(id);
// store our object
objectMapper.set(id, el);
})
// we assign the uniqueSet to be the interesction of uniqueSet and currentIds. if uniqueSet is undefined, give us everything.
uniqueSet = currentIds.intersection(uniqueSet ?? currentIds);
}
// spread into an array and get our objects.
return [...uniqueSet].map((id)=>objectMapper.get(id));
}
resolve(getUniqueObjectsFromMultipleArrays(
"id",
filter.title && byTitle,
filter.duration && byDuration,
filter.ingredient && byIngredient
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment