0

I have an array Order[], where Order is:

interface Order {
    orderId: number;        
    productName: string;
    color: string;
    quantity: number;
    price: number;
    link: string;
}

I want to create a mapping where:

  • key is (productName, color)
  • values are quantity, price, link. Quantity and price are a sum of matching properties of original objects. link is the same for all so can just keep one of them.

I know how to create a single item using filter and reduce, similar to this question: How to sum values in typescript array based on array items property?

I tried to use a Map object, but got stuck because I couldn't compare the keys properly - always got false

1 Answer 1

0

There's probably a more elegant way, but you could use a string template to represent the product/color combination.

Playground Link

interface Order {
    orderId: number;        
    productName: string;
    color: string;
    quantity: number;
    price: number;
    link: string;
}

interface Summary {
    productName: string;
    color: string;
    quantity: number;
    price: number;
}

const makeKey = (order: Order) => {
    return `${order.productName}_${order.color}`;
}

type AggregatedOrders = {
  [key: string]: Summary;
};
  
const orders: Order[] = [
    {
        color: "blue",
        link: "https://savantly.net",
        orderId: 123,
        price: 999,
        productName: "hello",
        quantity: 1
    },
    {
        color: "green",
        link: "https://savantly.net",
        orderId: 345,
        price: 999,
        productName: "hello",
        quantity: 1
    },
    {
        color: "green",
        link: "https://savantly.net",
        orderId: 234,
        price: 999,
        productName: "hello",
        quantity: 1
    }
];

const groups: AggregatedOrders = {};
orders.forEach(o => {
    const key = makeKey(o);
    if(!groups[key]) {
        groups[key] = o;
    } else {
        groups[key].price += o.price;
        groups[key].quantity + o.quantity
    }
});
// grouped by product and color
console.log(groups);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.