What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the 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);
    }
}

In order to accomplish this task, I require the Object Key.

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];
    }
}

The aim is to obtain separate arrays grouped by _shop_id from the products array. Here's a sample:

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} ]`

Answer №1

To access the _shop_id within a nested object, it is recommended to use a lambda function for extraction:

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());
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Issues with CSS/JQuery menu functionality experienced in Firefox`

After creating a toggleable overlay menu and testing it in various browsers, including Internet Explorer, everything seemed to work fine except for one major issue in Firefox (version 46). The problem arises when toggling the overlay using the "MENU" butt ...

What is the best way to tailor specific text in d3.js?

I need assistance with customizing the appearance of an asterisk added to the end of a template literal in d3js. I want to be able to independently adjust the size and color of the asterisk regardless of the variable it's attached to. Below is the cod ...

Challenges with extracting and organizing dates using JavaScript regular expressions

My task involves organizing these text rows into specific groups based on certain criteria and names. Il Messaggero Roma 22 settembre 2023 Il Messaggero Roma 21 settembre 2023 Il Messaggero 22 settembre 2023 Il Messaggero 21 settembre 2023 Il Messaggero Ro ...

Executing password validation on login/register form using Node.js and EJS

In order to demonstrate a simple login page, I have created a form that requests typical information like username, password, etc. Additionally, it prompts the user to confirm their password, and if the lengths do not match, an error is triggered to notify ...

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

How to handle blank property values in JavaScript objects and convert them to null in an ASP.NET Web API

Hey there! I'm facing an issue where when I post a JavaScript object to an ASP.NET Web API, some property values are blank like the example below: var o={ ID=1, Fname="Tom", Mname="", Lname="Wilson" } However, in the Web ...

Looking for a Webpack setup for a React Components Library that includes Typescript, SASS, CSS Modules, and SASS support

I'm on the lookout for a functional Webpack configuration tailored for a React Components Library that includes TypeScript, SASS, and CSS Modules with SASS support. If anyone has one they'd like to share, I would be extremely grateful! ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

What distinguishes p[0]++ from *(p)++ in the C programming language?

After attempting to run the following C code snippet: #include <stdio.h> int main(void) { int arr[] = {10, 20}; int *p = arr; p[0]++; // *(p)++; printf("arr[0] = %d, arr[1] = %d",arr[0], arr[1]); return 0; } Output: ...

How to access event.target in Internet Explorer 8 with unobtrusive Javascript

Here is a function that retrieves the target element from a dropdown menu: function getTarget(evt){ var targetElement = null; //if it is a standard browser if (typeof evt.target != 'undefined'){ targetElement = evt.target; } //otherwise ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...

What are some ways to display unprocessed image data on a website using JavaScript?

I have an API endpoint that provides image files in raw data format. How can I display this image data on a website using the img tag or CSS background-image property, without utilizing canvas? One possible approach is shown below: $.get({ url: '/ ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

What is the method for obtaining an element with a class name that does not match a specific value?

I'm trying to figure out how to select an element with a class name that is different from the value passed in. For example: $(document).ready(function () { $(document).on('change', '#allRolesDD', function () { var toS ...

Finding the chosen selection in AngularJs

I've been working on this script for hours and I'm struggling to output the text instead of the value of a select option in AngularJS in HTML through data binding. Despite my efforts, I keep getting the value instead of the text. How can I resolv ...

Combine various one-dimensional arrays into a new two-dimensional array in Python

Consider the scenario presented below: # z represents an empty object or potentially an empty 2D-array N = 2 for i in range(N): l = i * array([2,2,2]) # z.function(l) Is there a method or function available to append multiple 1D-arrays to an e ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Managing HTTP errors using async/await and the try/catch block in a React application with TypeScript

Below is a snippet of code I am working with! import React, { useState } from "react"; function App() { const [movies, setMovies] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState<string ...

Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database. Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.updat ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...