javascript group objects by property code example

Example 1: javascript group by property array of objects

function groupArrayOfObjects(list, key) {
  return list.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);//will be the Males 
console.log(groupedPeople.Female);//will be the Females

Example 2: 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 3: group objects in javascript

function groupBy(arr, prop) {
    const map = new Map(Array.from(arr, obj => [obj[prop], []]));
    arr.forEach(obj => map.get(obj[prop]).push(obj));
    return Array.from(map.values());
}

const data = [{ name: "Display", group: "Technical detals", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical detals", id: 37, value: "Apple iOS" }];
	
console.log(groupBy(data, "group"));

Example 4: javascript group by key

result = array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {})

Example 5: javascript array group by id

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

Example 6: javascript for group object properties based on another property

var list = [
     {   date: "2017-01-01",
         type: "type1",
         amount: 100
     },
     {   date: "2017-01-01",
         type: "type2",
         amount: 150
     },
     {   date: "2017-01-02",
         type: "type1",
         amount: 200
     }]

var dateArrKeyHolder = [];
var dateArr = [];
list.forEach(function(item){
    dateArrKeyHolder[item.date] = dateArrKeyHolder[item.date]||{};
    var obj = dateArrKeyHolder[item.date];
    if(Object.keys(obj).length == 0)
    dateArr.push(obj);
    
    obj.date = item.date;
    obj.activities  = obj.activities || [];
    
    obj.activities.push({type:item.type, amount: item.amount });
});


console.log(JSON.stringify(dateArr));

/* Result:
 [{"date":"2017-01-01","activities":[{"type":"type1","amount":100},{"type":"type2","amount":150}]},
  {"date":"2017-01-02","activities":[{"type":"type1","amount":200}]}] 
*/