How to groupBy in vanilla javascript
Currently i need to work with javascript more and more. So, i have to learn how to do same tricks i did in python/java/swift/etc in javascript :) Recenlty I needed to group some data by key and first thing that came to my mind is to use lodash .groupBy.
But this will require you to add one more package to your project. In case if you need to use it only once in some small app (AWS Lambda for example), then it would be much better to have a plain javascript method that will save you some time and space while developing another serverless app :). So, 5 minutes of search and smart people from stackoverflow helped me to find the answer :
const groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
You can use default keys that every javascript object has:
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}
Or use your own custom field:
data = [ { env: 'acceptance', fileName: 'acceptance-1234-mochaawesomereport.json' },
{ env: 'acceptance', fileName: 'acceptance-1234-mochawesomereport1.json' },
{ env: 'acceptance', fileName: 'acceptance-1234-mochawesomereport2.json' },
{ env: 'dev', fileName: 'dev-1234-mochaawesomereport.json' },
{ env: 'dev', fileName: 'dev-1234-mochawesomereport1.json' },
{ env: 'dev', fileName: 'dev-1234-mochawesomereport2.json' },
{ env: 'dev', fileName: 'dev-1234-mochawesomereport3.json' } ]
groupedData = groupBy(data, 'env')
// =>
// {
// "acceptance": [
// {
// "env": "acceptance",
// "fileName": "acceptance-1234-mochaawesomereport.json"
// },
// {
// "env": "acceptance",
// "fileName": "acceptance-1234-mochawesomereport1.json"
// },
// {
// "env": "acceptance",
// "fileName": "acceptance-1234-mochawesomereport2.json"
// }
// ],
// "dev": [
// {
// "env": "dev",
// "fileName": "dev-1234-mochaawesomereport.json"
// },
// {
// "env": "dev",
// "fileName": "dev-1234-mochawesomereport1.json"
// },
// {
// "env": "dev",
// "fileName": "dev-1234-mochawesomereport2.json"
// },
// {
// "env": "dev",
// "fileName": "dev-1234-mochawesomereport3.json"
// }
// ]
// }
So, thanks Ceasar Bautista for this nice tip :)
Happy coding guys.