JSFiddle - React, Tailwind, and code Playground
HTML
Product 1: <button id="product1">Add one</button>
<br>
Product 2: <button id="product2">Add one</button>
<div></div>
JavaScript
var cart = new Array();
$(document).ready(function(){
$('button').on('click', function() {
var pid = $(this).attr('id');
cart[cart.length] = {id:pid, qty:1}
var result = cart.reduce(function(res, obj) {
if (!(obj.id in res))
res.__array.push(res[obj.id] = obj);
else {
res[obj.id].qty += obj.qty;
}
return res;
}, {__array:[]})
console.log(result)
});
});