I'm trying to aggregate data using the reduce()
function in javascript (similar to this question):
HTML
Product 1: <button id="product1">Add one</button>
Product 2: <button id="product2">Add one</button>
JS
$('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)
});
});
I'm unable to make it work as the array being return doesn't contain the qty
data. E.g.:
Object {__array: Array[1], product1: Object}
Object {__array: Array[1], product1: Object}
Object {__array: Array[2], product1: Object, product2: Object}
The result I'm looking for is more like:
Object {product1: 1} //click on product1, quantity = 1
Object {product1: 2} //click on product1 again, quantity = 1 + 1 = 2
Object {product1: 2, product2: 1} //click on product2
What am I missing?