Skip to content

Instantly share code, notes, and snippets.

@Shridhad
Last active April 17, 2019 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shridhad/b3841e5967ae6d0334ed22e685b63085 to your computer and use it in GitHub Desktop.
Save Shridhad/b3841e5967ae6d0334ed22e685b63085 to your computer and use it in GitHub Desktop.
groupBy array
/**
* PROBLEM: Group an array of objects by a common key value.
* For example - Group cars by color.
*
* Following method also handle if the value is an array.
**/
const groupBy = key => array => {
const addEle = (k, v, o) => o[k] = (o[k] || []).concat(v);
return array.reduce((output, obj) => {
[].concat(obj[key]).forEach(v => addEle(v, obj, output));
return output;
}, {});
};
const cars = [
{ brand: 'Audi',, color: 'black' },
{ brand: 'Audi', color: ['white', 'black'] },
{ brand: 'Ferarri', color: 'red' },
{ brand: 'Ford', color: 'white' },
{ brand: 'Peugot', color: 'white' }
];
console.log(
JSON.stringify({
carsByColor: groupBy('color')(cars)
}, null, 2)
);
/* Should result following
{
"black": [
{"brand": "Audi", "color": "black"},
{"brand": "Audi", "color": ["white", "black"]}
],
"white": [
{"brand": "Audi", "color": ["white", "black"]},
{"brand": "Ford", "color": "white"},
{"brand": "Peugot","color": "white"}
],
"red": [
{"brand": "Ferarri", "color": "red"}
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment