Last active
March 8, 2017 20:07
-
-
Save krhancoc/c6503dd50859736c5707734c914729a8 to your computer and use it in GitHub Desktop.
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
/** | |
* This will group a list of JSON objects (or any object) by a specific value defined by the user | |
* | |
* @example Example of a JSON object | |
* let example = [ | |
* { | |
* name: 'hello' | |
* }, | |
* { | |
* name: 'team' | |
* } | |
* ]; | |
* let grouped = groupBy(example, 'name.charAt.toUpperCase', [0,null]); | |
* // Returns the object where 'H' and 'T' are valid keys. | |
* Output = { | |
* H: [ { name: 'hello'}], | |
* T: [ { name: 'team'}], | |
* } | |
* @example Example using strings | |
* const l = ['hello', 'hellz', 'foobar', 'foo']; | |
* | |
* const expected = { | |
* HE: ['hello', 'hellz'], | |
* FO: ['foobar', 'foo'] | |
*}; | |
* | |
* groupBy(l,'substring.toUpperCase',[[0,2],null]) == expected; | |
* //returns true | |
* @param {Array} list List of objects | |
* @param {string} func Period seperated function calls or key calls | |
* @param {Array} passIn list of values that will be passed into whatever functions are encountered in the func string | |
* ORDER DOES MATTER | |
* @returns {{}} Dictionary object with each key being the value you specified by user, and key values being the objects | |
* that fall into that category. | |
* @memberOf Utilities | |
* | |
*/ | |
groupBy: (list, func, passIn) => { | |
const isIterable = (object) => { | |
return object !== null && typeof object[Symbol.iterator] === 'function'; | |
}; | |
return list.reduce((acc, val) => { | |
const calls = func.split('.'); | |
let p = -1; | |
const t = calls.reduce((a,c) => { | |
if (typeof a[c] === 'function') { | |
const f = a[c].bind(a); | |
return f.apply(f, isIterable(passIn[++p]) ? passIn[p] : [passIn[p]]); | |
} | |
return a[c]; | |
}, val); | |
if (t in acc){ | |
acc[t].push(val); | |
} | |
else { | |
acc[t] = [val]; | |
} | |
return acc; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment