Home > Blockchain >  How to compress duplicate elements and get their quantity values?
How to compress duplicate elements and get their quantity values?

Time:12-07

I need to find the elements with the same id in the array below, add their amounts and write them in a single line.

 let arr = [
{ itemId: 123, name: '0', quantity: 2 },
{ itemId: 1, name: '1', quantity: 2 },
{ itemId: 13, name: '2', quantity: 2 },
{ itemId: 13, name: '3', quantity: 2 },
{ itemId: 13, name: '4', quantity: 24 },
{ itemId: 13, name: '5', quantity: 2 },
{ itemId: 1, name: '6', quantity: 4 },
{ itemId: 1, name: '7', quantity: 2 },];
  

I want an output like this:

[{ itemId: 123, name: '1', quantity: 2 },
{ itemId: 1, name: '2', quantity: 6 },
{ itemId: 13, name: '6', quantity: 30 }];

And my code:

const getPureList = () => {
    for (let index = 0; index < arr.length; index  ) {
      for (let a = index   1; a < arr.length; a  ) {
        if (arr[index].itemId === arr[a].itemId) {
          arr[index].quantity  = arr[a].quantity;
          arr.splice(a, 1);
        }
      }
    }
    return arr;
  };

Thanks for your help.

CodePudding user response:

By keeping the name od the first object of the group, you could take an object for grouping and take the values as result.

const
    array = [{ itemId: 123, name: '0', quantity: 2 }, { itemId: 1, name: '1', quantity: 2 }, { itemId: 13, name: '2', quantity: 2 }, { itemId: 13, name: '3', quantity: 2 }, { itemId: 13, name: '4', quantity: 24 }, { itemId: 13, name: '5', quantity: 2 }, { itemId: 1, name: '6', quantity: 4 }, { itemId: 1, name: '7', quantity: 2 }],
    result = Object.values(array.reduce((r, o) => {
        r[o.itemId] ??= { ...o, quantity: 0 };
        r[o.itemId].quantity  = o.quantity;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related