0

I have a array as follows :

data = [
{
 "type":"abc",
 "quantity":36,
 "code:"EDF"
},
{
 "type":"abc",
 "quantity":40
 "code:"SFDF"
},
{
 "type":"yrf",
 "quantity":22
 "code:"SFDF"
},
{
 "type":"yrf",
 "quantity":19
 "code:"EDF"
}
]

I want to group elements of this array on the basis of type and code. for example, if type is "abc", then I want to include new attributes for quantity of EDF as "quantity_EDF",and quantity of SFDF as "quantity_SFDF". So my resultant array will look as follows:

resultantArray = [
{
"type":"abc",
"quantity_EDF":36,
"quantity_SFDF":40
},
{
"type":"yrf",
"quantity_EDF":19,
"quantity_SFDF":22
}
]

How can I do this?

Rosy
  • 71
  • 4
  • [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – CBroe Apr 24 '23 at 11:59

2 Answers2

1

You can use reduce with destructuring and coalescing operator ??

const data = [
  {
    "type": "abc",
    "quantity": 36,
    "code": "EDF"
  },
  {
    "type": "abc",
    "quantity": 40,
    "code": "SFDF"
  },
  {
    "type": "yrf",
    "quantity": 22,
    "code": "SFDF"
  },
  {
    "type": "yrf",
    "quantity": 19,
    "code": "EDF"
  }
];

const result = Object.values(data.reduce((acc, { type, quantity, code }) => {
  acc[type] ??= { type };
  acc[type][`quantity_${code}`] ??= 0;
  acc[type][`quantity_${code}`] += quantity;
  return acc;
}, {}));


console.log(result);

If you dont want to use ?? you can use || operator instead. It returns the left side value if it's truthy, otherwise it returns the right side.

const data = [
  {
    "type": "abc",
    "quantity": 36,
    "code": "EDF"
  },
  {
    "type": "abc",
    "quantity": 40,
    "code": "SFDF"
  },
  {
    "type": "yrf",
    "quantity": 22,
    "code": "SFDF"
  },
  {
    "type": "yrf",
    "quantity": 19,
    "code": "EDF"
  }
];




const result = Object.values(data.reduce((acc, { type, quantity, code }) => {
  acc[type] = acc[type] || { type };
  acc[type][`quantity_${code}`] = (acc[type][`quantity_${code}`] || 0) + quantity;
  return acc;
}, {}));

console.log(result);
protob
  • 3,317
  • 1
  • 8
  • 19
  • at = in ??= I am getting error Expression expected in vs code – Rosy Apr 24 '23 at 12:29
  • More info please. Are you using some code linter? If so, this syntax is a quite new feature and it's possible that you are using the old version or some config that doesn't support it. – protob Apr 24 '23 at 12:41
0

Hope this will help

const resultOfArray = [];

data.forEach((item) => {
  const { type, code, quantity } = item;
  const group = resultOfArray.find((ty) => ty.type === type) || { type };

  group[`quantity_${code}`] = (group[`quantity_${code}`] || 0) + quantity;

  if (!resultOfArray.includes(group)) {
    resultOfArray.push(group);
  }
});

console.log(resultOfArray);
  • could you please add comment for explanation of your code. I am finding it bit difficult to understand – Rosy Apr 24 '23 at 12:20