Ethan Cox
Ethan Cox

Reputation: 78

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'
 },
 {
    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'
 }]

how do i conver it to look like below

lineitems : [{
    quantity : 2,
    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'
 }]

basically looking to merge duplicates based on SKU

Upvotes: 1

Views: 110

Answers (4)

Leo Nix
Leo Nix

Reputation: 2105

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>

Upvotes: 0

Daniel Rosano
Daniel Rosano

Reputation: 695

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

Upvotes: 1

user1776684
user1776684

Reputation: 1

Using lodash is a quick way to manage your collections:

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

Upvotes: 0

Arash R
Arash R

Reputation: 141

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;
});

Upvotes: 1

Related Questions