3

I have an array products that needs to be grouped by Product._shop_id.

export class Product {
    _id: string;
    _shop_id: string;
}

export class Variant { variant_id: string; }

export interface ShoppingCart {
    Variant: Variant;
    Product: Product;
    quantity: number;
    totalPrice: number;
}

export class CartComponent implements OnInit {
    products: ShoppingCart[] = [];

    ngOnInit(){
      this.products = [
                        {Variant: {variant_id: '1'}, Product: {_id: '1', _shop_id:'1'}, quantity: 5, totalPrice: 600},
                        {Variant: {variant_id: '2'}, Product: {_id: '2', _shop_id:'2'}, quantity: 4, totalPrice: 500},
                        {Variant: {variant_id: '5'}, Product: {_id: '3', _shop_id:'2'}, quantity: 3, totalPrice: 400}
                      ]
    }

    someMethod(){
      const productsByShop = this.utils.groupBy(this.products, key);
    }
}

Here is the method to achieve this. But I need the Object Key to make it work.

export class Utils {
    constructor() { }

    groupBy(list, key) {
        const map = new Map();
        list.forEach((item) => {
            const collection = map.get(key);
            if (!collection) {
                map.set(key, [item]);
            } else {
                collection.push(item);
            }
        });
        return Array.from(map)[0][1];
    }
}

I'm trying to get different arrays grouped by _shop_id from products array. Like this:

array1: [ {Variant: {variant_id: '1'}, Product: {_id: '1', _shop_id:'1'}, quantity: 5, totalPrice: 600} ]`

array2: [ {Variant: {variant_id: '2'}, Product: {_id: '2', _shop_id:'2'}, quantity: 4, totalPrice: 500},
          {Variant: {variant_id: '5'}, Product: {_id: '3', _shop_id:'2'}, quantity: 3, totalPrice: 400} ]`

1 Answer 1

12

Since your _shop_id belongs to a nested object, you're probably best off passing a lambda to extract it:

someMethod(){
  const productsByShop = this.utils.groupBy(this.products,
    (product) => product.Product._shop_id);
}
// ...
export class Utils {
    constructor() { }

    groupBy<T, K>(list: T[], getKey: (item: T) => K) {
        const map = new Map<K, T[]>();
        list.forEach((item) => {
            const key = getKey(item);
            const collection = map.get(key);
            if (!collection) {
                map.set(key, [item]);
            } else {
                collection.push(item);
            }
        });
        return Array.from(map.values());
    }
}
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.