I have an array like the following.
[ { sku: 'TEA-BLCK', price: '10', quantity: '1' },
{ sku: 'TEA-ELGY', price: '10', quantity: '1' },
{ sku: 'TEA-CHAI', price: '10', quantity: '1' },
{ sku: 'TEA-GREN', price: '10', quantity: '1' },
{ sku: 'TEA-ELGY', price: '10', quantity: '1' },
{ sku: 'TEA-MINT', price: '10', quantity: '1' } ]
I need to make it look like this
[ { sku: 'TEA-BLCK', price: '10', quantity: '1' },
{ sku: 'TEA-ELGY', price: '10', quantity: '2' },
{ sku: 'TEA-CHAI', price: '10', quantity: '1' },
{ sku: 'TEA-GREN', price: '10', quantity: '1' },
{ sku: 'TEA-MINT', price: '10', quantity: '1' } ]
I got so far to make this reduce function using underscore.js.
var reduce = function(){
return _.reduce(line_items, function(quant, item) {
quant[item.sku] = (typeof(quant[item.sku]) !== "undefined") ? quant[item.sku] : 0 ;
quant[item.sku] = parseFloat(item.quantity) + quant[item.sku];
return quant;
}, {});
}
Which spits out the following.
{ 'TEA-BLCK': 1,
'TEA-ELGY': 1,
'TEA-CHAI': 2,
'TEA-GREN': 1,
'TEA-MINT': 1 }
Is this a good job for reduce? How can I get it the way I want?
reduceis not well suitable for this task. Consider starting withgroupByand thenmap.