Skip to content

Instantly share code, notes, and snippets.

@wassname
Last active March 8, 2016 02:47
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 wassname/a53443b867a059fa9f61 to your computer and use it in GitHub Desktop.
Save wassname/a53443b867a059fa9f61 to your computer and use it in GitHub Desktop.
invertByMany
// use lodash and es6 to invert a Object by subvalues. This let's you catalouge subvalues by keys
/**
* inverts a object by many values
* e.g. invertByMany({ 'a': [1,2,3], 'b': [1], c:[2]})
* // {"1":["a","b"],"2":["a","c"],"3":["a"]}
**/
var invertByMany=(dataObj)=>
_.transform(dataObj, (result, values, key)=>
_.map(values,subvalue=>
(result[subvalue] || (result[subvalue] = [])).push(key))
, {})
/**
* inverts a object by many unique values
* inveryByUniqueValues({ 'a': [1,2], 'b': [3], c:[4]})
* // {1: "a", 2: "a", 3: "b", 4:"c"}
*/
export var invertByUniqueValues = function (dataObj) {
return _.transform(dataObj, (a, v, k) =>
_.map(v, sv => a[sv] = k), {})
}
// P.S.
// es5 version of invertByMany
function invertByMany(dataObj){
return _.transform(dataObj, function(result, values, key){
return _.map(values,function(subvalue){
if (!result[subvalue]) result[subvalue] = []
result[subvalue].push(key)
return result;
})
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment