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?
I was a bit late to the party, but it sounded so fun, so..
Here we pre-sort the array, and then add elements to the beginning of accumulator. And GGG have already said about strings.
http://jsfiddle.net/EqGUe/
Technically this is the complete answer. From string to string. Sorry guys.
What about a simple solution like this:
http://jsfiddle.net/waV6H/1
Probably the only thing that needs explanation here is the line where we subtract a negative instead of adding. This is just to avoid string concatenation, since the values in "quantity" are strings.
Super condensed version, dropping unneeded braces and semicolons... just for fun. Preserves order and quantity as string, works with quantity != 1.
Try something like this:
See this jsfiddle.
A bit late as well, but fun to work out http://jsbin.com/amazat/2/
This updates benekastah's answer and handles quantities more than 1... But I did take the liberty to change quantity to an integer
http://jsfiddle.net/xjUDY/3/