Created
September 14, 2018 07:38
-
Star
(254)
You must be signed in to star a gist -
Fork
(62)
You must be signed in to fork a gist
-
-
Save JamieMason/0566f8412af9fe6a1d470aa1e089a752 to your computer and use it in GitHub Desktop.
Revisions
-
JamieMason created this gist
Sep 14, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,112 @@ # Group Array of JavaScript Objects by Key or Property Value ## Implementation ```js const groupBy = key => array => array.reduce((objectsByKeyValue, obj) => { const value = obj[key]; objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj); return objectsByKeyValue; }, {}); ``` Or using an implicit return (slower): ```js const groupBy = key => array => array.reduce( (objectsByKeyValue, obj) => ({ ...objectsByKeyValue, [obj[key]]: (objectsByKeyValue[obj[key]] || []).concat(obj) }), {} ); ``` ## Usage ```js const cars = [ { brand: 'Audi', color: 'black' }, { brand: 'Audi', color: 'white' }, { brand: 'Ferarri', color: 'red' }, { brand: 'Ford', color: 'white' }, { brand: 'Peugot', color: 'white' } ]; const groupByBrand = groupBy('brand'); const groupByColor = groupBy('color'); console.log( JSON.stringify({ carsByBrand: groupByBrand(cars), carsByColor: groupByColor(cars) }, null, 2) ); ``` ### Output ```json { "carsByBrand": { "Audi": [ { "brand": "Audi", "color": "black" }, { "brand": "Audi", "color": "white" } ], "Ferarri": [ { "brand": "Ferarri", "color": "red" } ], "Ford": [ { "brand": "Ford", "color": "white" } ], "Peugot": [ { "brand": "Peugot", "color": "white" } ] }, "carsByColor": { "black": [ { "brand": "Audi", "color": "black" } ], "white": [ { "brand": "Audi", "color": "white" }, { "brand": "Ford", "color": "white" }, { "brand": "Peugot", "color": "white" } ], "red": [ { "brand": "Ferarri", "color": "red" } ] } } ```