Example 1: javascript group by key
var 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' }],
result = cars.reduce(function (r, a) {
r[a.make] = r[a.make] || [];
r[a.make].push(a);
return r;
}, Object.create(null));
console.log(result);
Example 2: javascript group by key
result = array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {})
Example 3: lodash groupby return array
let arr = [{
"birthdate": "1993",
"name": "Ben"
},
{
"birthdate": "1994",
"name": "John"
},
{
"birthdate": "1995",
"name": "Larry"
},
{
"birthdate": "1995",
"name": "Nicole"
},
{
"birthdate": "1996",
"name": "Jane"
},
{
"birthdate": "1996",
"name": "Janet"
},
{
"birthdate": "1996",
"name": "Dora"
},
];
const res = arr.reduce((ac, a) => {
let temp = ac.find(x => x.birthdate === a.birthdate);
if (!temp) ac.push({ ...a,
name: [a.name]
})
else temp.name.push(a.name)
return ac;
}, [])
console.log(res);
Example 4: lodash groupby return array
export const groupArrayBy = (arr, groupBy) => {
let newArr = []
arr.map((item) => {
if(item[groupBy]) {
let finded = newArr.filter((newItem) => newItem[groupBy] === item[groupBy])
if(finded.length > 0) {
finded[0].products.push(item)
} else {
newArr.push({category: item[groupBy], products: [item]})
}
}
})
return newArr
}
Example 5: lodash groupby return array
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
Example 6: lodash groupby unique array of objects
{ audi:
[ { model: 'r8', year: '2012' },
{ model: 'rs5', year: '2013' } ],
ford:
[ { model: 'mustang', year: '2012' },
{ model: 'fusion', year: '2015' } ],
kia:
[ { model: 'optima', year: '2012' } ]
}