Based on this example, I want to group by object in a slightly other way. The outcome should be as follows:
[{
key: \"audi\"
items: [
{
\"make\": \
You could use a hash table for grouping by make
and an array for the wanted result.
For every group in hash
, a new object, like
{
key: a.make,
items: []
}
is created and pushed to the result set.
The hash table is initialized with a really empty object. There are no prototypes, to prevent collision.
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' }],
hash = Object.create(null),
result = [];
cars.forEach(function (a) {
if (!hash[a.make]) {
hash[a.make] = { key: a.make, items: [] };
result.push(hash[a.make]);
}
hash[a.make].items.push(a);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }