Last active
December 4, 2020 18:01
-
-
Save wattry/de36aa0fdecbab93adbaf4ff7818ef94 to your computer and use it in GitHub Desktop.
Group arrays by key using Array.prototype.reduce in Javascript
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
/** | |
* Groups an array of objects by a key an returns an object or array grouped by provided key. | |
* @param array - array to group objects by key. | |
* @param key - key to group array objects by. | |
* @param removeKey - remove the key and it's value from the resulting object. | |
* @param outputType - type of structure the output should be contained in. | |
*/ | |
const groupBy = ( | |
inputArray, | |
key, | |
removeKey = false, | |
outputType = {}, | |
) => { | |
return inputArray.reduce( | |
(previous, current) => { | |
// Get the current value that matches the input key and remove the key value for it. | |
const { | |
[key]: keyValue | |
} = current; | |
// remove the key if option is set | |
removeKey && keyValue && delete current[key]; | |
// If there is already an array for the user provided key use it else default to an empty array. | |
const { | |
[keyValue]: reducedValue = [] | |
} = previous; | |
// Create a new object and return that merges the previous with the current object | |
return Object.assign(previous, { | |
[keyValue]: reducedValue.concat(current) | |
}); | |
}, | |
// Replace the object here to an array to change output object to an array | |
outputType, | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment