Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav
Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:
var result = {};
for ( let { first_field, ...fields } of your_data )
{
result[first_field] = result[first_field] || [];
result[first_field].push({ ...fields });
}
I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.
Here is another solution to it. As requested.
I want to make a new array of car objects that's grouped by make:
function groupBy() {
const key = 'make';
return cars.reduce((acc, x) => ({
...acc,
[x[key]]: (!acc[x[key]]) ? [{
model: x.model,
year: x.year
}] : [...acc[x[key]], {
model: x.model,
year: x.year
}]
}), {})
}
Output:
console.log('Grouped by make key:',groupBy())
Here is your very own groupBy
function which is a generalization of the code from: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore
function groupBy(xs, f) {
return xs.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});
}
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];
const result = groupBy(cars, (c) => c.make);
console.log(result);
Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.
Array.prototype.groupBy = function(k) {
return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
};
const projs = [
{
project: "A",
timeTake: 2,
desc: "this is a description"
},
{
project: "B",
timeTake: 4,
desc: "this is a description"
},
{
project: "A",
timeTake: 12,
desc: "this is a description"
},
{
project: "B",
timeTake: 45,
desc: "this is a description"
}
];
console.log(projs.groupBy("project"));
I made a benchmark to test the performance of each solution that don't use external libraries.
JSBen.ch
The reduce()
option, posted by @Nina Scholz seems to be the optimal one.
Grouped Array of Object in typescript with this:
groupBy (list: any[], key: string): Map<string, Array<any>> {
let map = new Map();
list.map(val=> {
if(!map.has(val[key])){
map.set(val[key],list.filter(data => data[key] == val[key]));
}
});
return map;
});