Last active
April 17, 2019 11:06
-
-
Save Shridhad/b3841e5967ae6d0334ed22e685b63085 to your computer and use it in GitHub Desktop.
groupBy array
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
/** | |
* 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