Last active
March 8, 2016 02:47
-
-
Save wassname/a53443b867a059fa9f61 to your computer and use it in GitHub Desktop.
invertByMany
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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