Skip to content Skip to sidebar Skip to footer

Javascript Group By In Array

I want to group an array that I have. For example: var shoppingCart = [ { productId: '123', price: 12,99 quantity: 1, shopId: 'abc', sho

Solution 1:

Use reduce to create an object with a key for each unique shop name. Push items to these arrays as you go along:

// Group objects in an array by a propertyvar mapBy = function(arr, groupName, propName) {
  return arr.reduce(function(result, item) {
    result[item[groupName]] = result[item[groupName]] || [];
    result[item[groupName]].push(item[propName]);
    return result;
  }, {});
};

var shoppingCart=[{productId:"123",price:12.99,quantity:1,shopId:"abc",shopName:"shop 1"},{productId:"457",price:83.33,quantity:2,shopId:"asw",shopName:"shop 2"},{productId:"4232",price:47.21,quantity:1,shopId:"abc",shopName:"shop 1"},{productId:"3332",price:9.99,quantity:4,shopId:"abc",shopName:"shop 1"},{productId:"33221",price:99.21,quantity:1,shopId:"asw",shopName:"shop 2"},{productId:"452113",price:22.45,quantity:2,shopId:"asdj",shopName:"shop 3"}];

console.log(mapBy(shoppingCart, "shopName", "productId"));

Solution 2:

You can use reduce() like this and return object.

var shoppingCart = [{"productId":"123","price":12,"quantity":1,"shopId":"abc","shopName":"shop 1"},{"productId":"457","price":83,"quantity":2,"shopId":"asw","shopName":"shop 2"},{"productId":"4232","price":47,"quantity":1,"shopId":"abc","shopName":"shop 1"},{"productId":"3332","price":9,"quantity":4,"shopId":"abc","shopName":"shop 1"},{"productId":"33221","price":99,"quantity":1,"shopId":"asw","shopName":"shop 2"},{"productId":"452113","price":22,"quantity":2,"shopId":"asdj","shopName":"shop 3"}]

var r = shoppingCart.reduce(function(r, e) {
  r[e.shopName] = (r[e.shopName] || []).concat({productId: e.productId})
  return r;
}, {})

console.log(r)

Solution 3:

I propose that using filter() method

varshoppingCart= [
{
    productId:'123',
    price:12.99,
    quantity:1,
    shopId:'abc',
    shopName:'shop 1'
},
{
    productId:'457',
    price:83.33,
    quantity:2,
    shopId:'asw',
    shopName:'shop 2'
},
{
    productId:'4232',
    price:47.21,
    quantity:1,
    shopId:'abc',
    shopName:'shop 1'
},
{
    productId:'3332',
    price:9.99,
    quantity:4,
    shopId:'abc',
    shopName:'shop 1'
},
{
    productId:'33221',
    price:99.21,
    quantity:1,
    shopId:'asw',
    shopName:'shop 2'
},
{
    productId:'452113',
    price:22.45,
    quantity:2,
    shopId:'asdj',
    shopName:'shop 3'
}
];varshop1=shoppingCart.filter(x=>x.shopName==='shop 1').map(x=>({productId:x.productId}));console.log(shop1);// [ { productId:'123' }, { productId:'4232' },{ productId:'3332' } ]

Post a Comment for "Javascript Group By In Array"