DEV Community

Miguel Ramirez
Miguel Ramirez

Posted on

Typescript - reduce to get total and items about a list

type Item = { item: string, price: number, count: number };
const listItems: Item[] = [{ item: "item_1", price: 1, count: 3 }, { item: "item_2", price: 2, count: 5 }]
const totalPurchase = listItems.reduce((acc, current) => {
    acc["purchasedItems"][current.item] = current.price * current.count;
    acc["total"] = acc["total"] + acc["purchasedItems"][current.item];
    return acc;
}, { total: 0, purchasedItems: {} } as any)

console.log(totalPurchase)
Enter fullscreen mode Exit fullscreen mode

example response:

[LOG]: {
  "total": 13,
  "purchasedItems": {
    "item_1": 3,
    "item_2": 10
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)