Created
October 23, 2019 14:38
-
-
Save dturton/a60f0ff42d7db88418f1970fb3d4daff to your computer and use it in GitHub Desktop.
group duplicate items in array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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