Skip to content

Instantly share code, notes, and snippets.

@jcottrell
Created March 23, 2017 20:46
Show Gist options
  • Save jcottrell/2ef4b6161fd0c6246ac921ecb4e9ebf6 to your computer and use it in GitHub Desktop.
Save jcottrell/2ef4b6161fd0c6246ac921ecb4e9ebf6 to your computer and use it in GitHub Desktop.
This is a function I wanted to keep somewhere until I found the library that did it better or had the time to implement ramdajs. It takes a couple functions and an array of objects. It returns an array of objects / values / results based on a unique value.
/* ok, ok, I needed a way to get unique values from objects
getUniqueIdFun should be a function that returns the value of what
you want to be unique
getUniquePartFun should be a function that returns the part of the
object you are interested in; it can be undefined, null, empty if
you want the whole object back
objAr should be an array of objects to cull from
*/
const getUniqueObjectsFromArray = (getUniqueIdFun, getUniquePartFun, objAr) => {
const getU = (typeof getUniquePartFun === 'function') ?
getUniquePartFun : o => o;
return objAr.reduce((soFar, obj) => {
const uniqueIdOfObject = getUniqueIdFun(obj);
const uniquePart = getU(obj);
return soFar.uniqueIds.indexOf(uniqueIdOfObject) >= 0 ?
soFar :
{ uniqueIds: soFar.uniqueIds.concat([uniqueIdOfObject]),
uniqueParts: soFar.uniqueParts.concat([uniquePart])};
}, {uniqueIds: [], uniqueParts: []}).uniqueParts;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment