Created
October 10, 2016 14:23
-
-
Save nash403/16cf19a75fd147db833a3a698ccd87bc to your computer and use it in GitHub Desktop.
Group array elements upon a criteria.
This file contains hidden or 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
/* | |
* @param property string, number or function. This is the crieteria of the grouping function | |
*/ | |
function groupBy(arr, property) { | |
return arr.reduce( (memo, el, i) => { | |
let grpProperty = (() => { | |
if (typeof property === 'string' || typeof property === 'number') { | |
return el[property]; | |
} else if (typeof property === 'function') { | |
return property(el, i, arr); | |
} | |
})(); | |
if (!grpProperty) return memo; | |
if (!memo[grpProperty]) { memo[grpProperty] = []; } | |
memo[grpProperty].push(el); | |
return memo; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment