Check out the item array provided below:
const items = [ { itemId: 123, quantity: 1, description: "TEST" }, { itemId: 123, quantity: 1, description: "TEST" }, { itemId: 123, quantity: 1, description: "TEST" }, { itemId: 456, quantity: 1, description: "TESTNEW" }, ];
We need to reduce this collection based on the itemId property and increment the quantity based on the same itemId. The expected output should be:
[ { itemId: 123, quantity: 3, description: "TEST" }, { itemId: 456, quantity: 1, description: "TESTNEW" }, ];
To achieve this, you can utilize Array.reduce in typescript to update the attributes and select only unique itemId values. Below is an example of typescript code used for this purpose:
export interface MiniBagItem {
name?: string;
sku?: string;
quantity?: number;
}
const item1: MiniBagItem = { name: "test", sku: "123", quantity: 1 };
const item2: MiniBagItem = { name: "test", sku: "123", quantity: 1 };
const item3: MiniBagItem = { name: "testNew", sku: "456", quantity: 1 };
const miniBagItems: MiniBagItem[] = [];
miniBagItems.push(item1, item2, item3);
//start reduce
let seenMap = new Map();
miniBagItems.reduce<MiniBagItem>((acc: MiniBagItem[], obj, index) => {
let seen = seenMap.get(obj.sku);
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
seen !== undefined
? acc[seen].quantity++
: (seenMap.set(obj.sku, index), acc.push(obj));
acc.push(obj);
return acc;
}, []);
//console.log(newItems);
export {};