Created
October 25, 2018 23:18
-
Star
(101)
You must be signed in to star a gist -
Fork
(12)
You must be signed in to fork a gist
-
-
Save robmathers/1830ce09695f759bf2c4df15c29dd22d to your computer and use it in GitHub Desktop.
A more readable and annotated version of the Javascript groupBy from Ceasar Bautista (https://stackoverflow.com/a/34890276/1376063)
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
var groupBy = function(data, key) { // `data` is an array of objects, `key` is the key (or property accessor) to group by | |
// reduce runs this anonymous function on each element of `data` (the `item` parameter, | |
// returning the `storage` parameter at the end | |
return data.reduce(function(storage, item) { | |
// get the first instance of the key by which we're grouping | |
var group = item[key]; | |
// set `storage` for this instance of group to the outer scope (if not empty) or initialize it | |
storage[group] = storage[group] || []; | |
// add this item to its group within `storage` | |
storage[group].push(item); | |
// return the updated storage to the reduce function, which will then loop through the next | |
return storage; | |
}, {}); // {} is the initial value of the storage | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
but the unexpected is
i have tried with
but its looping the result.
i have solved by add new function look like these
but i want the code is inside the group by as default .