group by id javascript code example

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: javascript array group by id

var results = orgs.reduce(function(results, org) {
    (results[org.id] = results[org.id] || []).push(org);
    return results;
}, {})

Example 4: group by in javascript

let group = cars.reduce((r, a) => { console.log("a", a); console.log('r', r); r[a.make] = [...r[a.make] || [], a]; return r;}, {});console.log("group", group);