Created
July 17, 2023 08:43
-
-
Save codeallday31/dd63a96581d0ae3a20ead2608448dd09 to your computer and use it in GitHub Desktop.
groupby
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
function _group_by(list, key) { | |
const groupBy = (array, key) => { | |
// Return the end result | |
return array.reduce((result, currentValue) => { | |
// If an array already present for key, push it to the array. Else create an array and push the object | |
(result[currentValue[key]] = result[currentValue[key]] || []).push( | |
currentValue | |
); | |
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate | |
return result; | |
}, []); // empty object is the initial value for result object | |
}; | |
// Group by key as key to the list array | |
return groupBy(list, key).filter(item => item); | |
}, |
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
function groupBy(data, key) { | |
return data.reduce(function(storage, item) { | |
const group = item[key]; | |
storage[group] = storage[group] || []; | |
storage[group].push(item); | |
return storage; | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment