Search code examples
javascriptgroupinglodash

group array of objects


Hi guys i've question about how to group by key id value and do sum on ( key harga value and key qty value) below are the array of objects:

order: [
  {
    id: 4,
    idkatg: 2,
    kategori: 'minuman',
    nmprod: 'es mambo',
    harga: 8000,
    qty: 1
  },
  {
    id: 4,
    idkatg: 2,
    kategori: 'minuman',
    nmprod: 'es mambo',
    harga: 8000,
    qty: 1
  }
]

what i wan't to achieve is like this :

order:[
   {
     id: 4,
     idkatg: 2,
     kategori: 'minuman',
     nmprod: 'es mambo',
     harga: 14000,
     qty: 2
   }
]

is there any solution using lodash maybe ?


Solution

  • You could reduce the object and find the object with the same id, then update. Otherwise push the actual object to the result set.

    If needed, you could take a sloppy copy with

    r.push(Object.assign({}, o));
    

    var order = [{ id: 4, idkatg: 2, kategori: 'minuman', nmprod: 'es mambo', harga: 8000, qty: 1 }, { id: 4, idkatg: 2, kategori: 'minuman', nmprod: 'es mambo', harga: 8000, qty: 1 }];
    
    order = order.reduce((r, o) => {
       var temp = r.find(({ id }) => id === o.id);
       if (temp) {
           ['harga', 'qty'].forEach(k => temp[k] += o[k]);
       } else {
           r.push(o);
       }
       return r;
    }, []);
    
    console.log(order);
    .as-console-wrapper { max-height: 100% !important; top: 0; }