aggregate - Unable to make native javascript reduce() function work -
i'm trying aggregate data using reduce()
function in javascript (similar 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 make work array being return doesn't contain 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 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 missing?
if want output object {product1: 2, product2: 1}
, using reduce
method, try below . passing initial value {}
reduce method syntax like
[].reduce( function( previousvalue, currentvalue, index, array ){}, initialvalue );
and our solution
var cart = []; $(document).ready(function(){ $('button').on('click', function() { cart.push( { id:$(this).attr('id'), qty:1 } ); var result = cart.reduce(function(res, obj) { if (!(obj.id in res )) { res[obj.id] = 0 } return ( res[obj.id] += obj.qty ) && res ; }, {} ) console.log( result ) }); });
and fiddle http://jsfiddle.net/c4wug/8/
Comments
Post a Comment