Anjo Bautista Liwanag
Anjo Bautista Liwanag

Reputation: 129

Getting summation an element of an array of a specific element

ARRAY 1

{
  parent: 'parent 1',
  occupiedStock: 0,
  sku: 'api-create-product-test-sample-1',
  shop: 'Remax Online'
}
{
  parent: 'parent 2',
  occupiedStock: 1,
  sku: 'API-TEST-PRODUCT-DO-NOT-USE-1',
  shop: 'Zealer Tech'
}
{
  parent: 'parent 2',
  occupiedStock: 2,
  sku: 'api-create-product-test-sample-5',
  shop: 'Remax Online'
}
{
  parent: 'parent 1',
  occupiedStock: 0,
  sku: '1591630793-1609218546440-0',
  shop: 'Remax Online'
}
{
  parent: 'parent 2',
  occupiedStock: 0,
  sku: 'api-create-product-test-sample-6',
  shop: 'Remax Online'
}
{
  parent: 'parent 1',
  occupiedStock: 1,
  sku: 'api-create-product-test-sample-8',
  shop: 'Remax Online'
}
{
  parent: 'parent 1',
  occupiedStock: 0,
  sku: 'api-create-product-test-sample-9',
  shop: 'Remax Online'
}
{
  parent: 'parent 2',
  occupiedStock: 2,
  sku: 'api-create-product-test-sample-7',
  shop: 'Remax Online'
}

I need to make an array that would make a summation of parent's occupied stock, ideally the new array would look like:

ARRAY 2

{
  parent: 'parent 1',
  totalOccupiedStock: 1,
}
{
  parent: 'parent 2',
  totalOccupiedStock: 5,
}

What's the best approach to merge occupied stocks of parents...

my post I guess are mostly codes, and I cannot proceed to post this question. I hope this is enough :)

Upvotes: 0

Views: 32

Answers (1)

phi-rakib
phi-rakib

Reputation: 3302

You could use Array.prototype.reduce() method. Traverse the array and make parent as key and based on that key sum the occupiedStock.

const data = [
  {
    parent: 'parent 1',
    occupiedStock: 0,
    sku: 'api-create-product-test-sample-1',
    shop: 'Remax Online',
  },
  {
    parent: 'parent 2',
    occupiedStock: 1,
    sku: 'API-TEST-PRODUCT-DO-NOT-USE-1',
    shop: 'Zealer Tech',
  },
  {
    parent: 'parent 2',
    occupiedStock: 2,
    sku: 'api-create-product-test-sample-5',
    shop: 'Remax Online',
  },
  {
    parent: 'parent 1',
    occupiedStock: 0,
    sku: '1591630793-1609218546440-0',
    shop: 'Remax Online',
  },
  {
    parent: 'parent 2',
    occupiedStock: 0,
    sku: 'api-create-product-test-sample-6',
    shop: 'Remax Online',
  },
  {
    parent: 'parent 1',
    occupiedStock: 1,
    sku: 'api-create-product-test-sample-8',
    shop: 'Remax Online',
  },
  {
    parent: 'parent 1',
    occupiedStock: 0,
    sku: 'api-create-product-test-sample-9',
    shop: 'Remax Online',
  },
  {
    parent: 'parent 2',
    occupiedStock: 2,
    sku: 'api-create-product-test-sample-7',
    shop: 'Remax Online',
  },
];

const ret = Object.values(
  data.reduce((prev, c) => {
    const p = prev;
    const key = c.parent;
    p[key] = p[key] ?? { parent: c.parent, occupiedStock: 0 };
    p[key].occupiedStock += c.occupiedStock;
    return p;
  }, {})
);
console.log(ret);

Upvotes: 2

Related Questions