Skip to content

Instantly share code, notes, and snippets.

@dturton
Created October 23, 2019 14:38
Show Gist options
  • Select an option

  • Save dturton/a60f0ff42d7db88418f1970fb3d4daff to your computer and use it in GitHub Desktop.

Select an option

Save dturton/a60f0ff42d7db88418f1970fb3d4daff to your computer and use it in GitHub Desktop.
group duplicate items in array
function groupItems(data) {
const group1 = data.reduce((sums, item) => {
const existingIndex = sums.findIndex(sum => sum.sku === item.sku);
const existing = sums[existingIndex];
if (!existing) return sums.concat(item);
return [
...sums.slice(0, existingIndex),
{
sku: item.sku,
quantity: existing.quantity + item.quantity
},
...sums.slice(existingIndex + 1)
];
}, []);
return group1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment