joisberg
joisberg

Reputation: 187

How to group same element in array

I have this array:

var cart = [
{
   name: "Pasta",
   price: "6.00",
},
{
   name: "Pizza",
   price: "4.00",
},
{
   name: "Pasta",
   price: "6.00",
},
{
   name: "Hot Dog",
   price: "2.00",
},
{
   name: "Pasta",
   price: "6.00",
},
{
   name: "Eggs",
   price: "3.00",
}
]

Now I print this array with:

var dataCart = "";
    for (i = 0; i < cart.length; i++){
    var rand = Math.floor(Math.random()*1000)+1;
        dataCart += "<div id='"+rand+"' class='row pb-3 mx-3 mt-3' style='border-bottom:1px solid #eeeeee;'>";
        dataCart += "<div id='fs-7' class='col-2 text-center font-weight-bold'>";
        dataCart += "1x";
        dataCart += "</div>";
        dataCart += "<div id='fs-7' class='col-5'>";
        dataCart += cart[i].title;
        dataCart += "</div>";
        dataCart += "<div class='col-3 font-weight-bold text-right' style='color:#27c727;' id='price-app'>";
        dataCart += parseFloat(cart[i].price).toFixed(2).toLocaleString()+" €";
        dataCart += "</div>";
        dataCart += "<div onclick='deleteItem("+i+","+rand+")' class='col-2'><img src='delete.png' style='max-height:20px;' class='img-fluid' /></div>";
        dataCart += "</div>";
    }

    $("#list-cart").html(dataCart);

With this code, I print all list of object

1x Pasta 6.00$<br>
1x Pizza 4.00$<br>
1x Pasta 6.00$<br>
1x Hot Dog 2.00$<br>
1x Pasta 6.00$<br>
1x Eggs 3.00$<br>

But I want to group for quantity > 1:

3x Pasta 18.00$<br>
1x Pizza 4.00$<br>
1x Hot Dog 2.00$<br>
1x Eggs 3.00$<br>

Upvotes: 0

Views: 134

Answers (4)

ganesh phirke
ganesh phirke

Reputation: 463

You can use groupBy and take simply length of the array for the count:-

use groupByResult for displaying your result.

var cart = [
  {
    name: "Pasta",
    price: "6.00",
  },
  {
    name: "Pizza",
    price: "4.00",
  },
  {
    name: "Pasta",
    price: "6.00",
  },
  {
    name: "Hot Dog",
    price: "2.00",
  },
  {
    name: "Pasta",
    price: "6.00",
  },
  {
    name: "Eggs",
    price: "3.00",
  },
];


function groupBy(groupBy) {
  var groupByResult = {};
  for (var ele of cart) {
    if (!groupByResult[ele[groupBy]]) {
      groupByResult[ele[groupBy]] = [];
    }
     groupByResult[ele[groupBy]].push(ele);
  }
  console.log(groupByResult);
}

groupBy("name")

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Build an object with values of quantity and price aggregation.

const group = (arr) => {
  const res = {};
  arr.forEach(({ name, price }) => {
    if (!res[name]) {
      res[name] = { name, quantity: 1, sub_total: Number(price) };
    } else {
      res[name].quantity += 1;
      res[name].sub_total += Number(price);
    }
  });
  return Object.values(res);
};

var cart = [
  {
    name: "Pasta",
    price: "6.00",
  },
  {
    name: "Pizza",
    price: "4.00",
  },
  {
    name: "Pasta",
    price: "6.00",
  },
  {
    name: "Hot Dog",
    price: "2.00",
  },
  {
    name: "Pasta",
    price: "6.00",
  },
  {
    name: "Eggs",
    price: "3.00",
  },
];



console.log(group(cart));

Upvotes: 0

Nick
Nick

Reputation: 16576

You can use the Array reduce method to reduce this down to an array of unique items with a new count property. You can use this new prop in your dataCart code.

var cart = [
{
   name: "Pasta",
   price: "6.00",
},
{
   name: "Pizza",
   price: "4.00",
},
{
   name: "Pasta",
   price: "6.00",
},
{
   name: "Hot Dog",
   price: "2.00",
},
{
   name: "Pasta",
   price: "6.00",
},
{
   name: "Eggs",
   price: "3.00",
}
]

const grouped = cart.reduce((acc, el) => {
  const found = acc.find(item => item.name === el.name);
  if (found) {
    found.count++;
    found.price += Number(el.price);
  } else {
    acc.push({...el, count: 1, price: Number(el.price)});
  }
  return acc;
}, [])

console.log(grouped);

Upvotes: 2

Rajneesh
Rajneesh

Reputation: 5308

You can reduce it and take values:

var cart = [{ name: "Pasta", price: "6.00",},{ name: "Pizza", price: "4.00",},{ name: "Pasta", price: "6.00",},{ name: "Hot Dog", price: "2.00",},{ name: "Pasta", price: "6.00",},{ name: "Eggs", price: "3.00",}];

var result = Object.values(cart.reduce((acc,{name, price})=>{
    acc[name] = acc[name] || {name, price:0, count:0 };
    acc[name].price+=+price;
    acc[name].count++;
    return acc;
},{}));

console.log(result);

Upvotes: 1

Related Questions