Skip to content Skip to sidebar Skip to footer

Merging Duplicates In Javascript Array

if i have a an array like below in JS lineitems : [{ quantity : 1, unitPrice : 10.00, unitPriceLessTax: 8.33, SKU: 'SKU123456', productName: 'Blue T-Shirt' },

Solution 1:

you can use associative array:

var newLineItems = new Array();
$.each(lineItems, function (index) {
    if (newLineItems[this.SKU])
        newLineItems[this.SKU].quantity += this.quantity;
    else
        newLineItems[this.SKU] = this;
});

Solution 2:

You can use Array.prototype.forEach()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

var result = []
var temp = [];
lineitems.forEach(function (element, index, array) {
    if (temp[element.SKU] === undefined)
        temp[element.SKU] = element;
    else
        temp[element.SKU].quantity += element.quantity;
});
for (var items in temp){
    result.push(temp[items]);
}

Hope it's useful

Dan


Solution 3:

Pure JS; Fast calculator;

<script>
    var lineItems = [{
    quantity : 1,
    unitPrice : 10.00,
    unitPriceLessTax: 8.33,
    SKU: 'SKU123456',
    productName: 'Blue T-Shirt'
 },
 {
    quantity : 1,
    unitPrice : 10.00,
    unitPriceLessTax: 8.33,
    SKU: 'SKU123456',
    productName: 'Blue T-Shirt'
 },
 {
    quantity : 1,
    unitPrice : 48.00,
    unitPriceLessTax: 40.00,
    SKU: 'SKU78910',
    productName: 'Red Shoes'
 }];

var nl =[], i=0;
var collapse = function ()
{
    if (lineItems.length<=i) return;
    if (nl[lineItems[i].SKU])
    {
        nl[lineItems[i].SKU].quantity+=lineItems[i].quantity;
    }
    else  nl[lineItems[i].SKU]=lineItems[i];
    i++;
    //lineItems.splice(0,1);
    collapse();
};
collapse();
console.log(nl);
var newLineItems = Object.keys(nl).map(function (key) {return nl[key]});
console.log(newLineItems);
console.log('new line items');
console.log(lineItems);
</script>

Solution 4:

Using lodash is a quick way to manage your collections:

result = _.uniq(lineitems, "SKU");

Post a Comment for "Merging Duplicates In Javascript Array"