How to separate an array of objects into individual arrays using Typescript reduce based on a specific property

I have the following array:

    statisticsOfScrapDeliveriesItems:[
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0180",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0085",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0085",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0180",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0065",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0065",
        }
    ]

The data type of this array is:

StatisticsOfScrapDeliveriesItems[]

What I am looking to do is separate the array into smaller arrays based on objects that share the same materialID, like so:

statisticsOfScrapDeliveriesItems:[
    TS0180: [
         {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0180",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0180",
        }
    ], 
    TS0085: [
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0085",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0085",
        },
    ],
    TS0065: [
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0065",
        },
        {
            supplierId: "0001055404",
            deliveredFrom: "METALLCO AS",
            centerId: "C45",
            materialId: "TS0065",
        }
    ]
]

This will allow me to easily access objects with a specific materialID.

I have come across solutions using JavaScript reduce, but since I am working in TypeScript, they are causing type errors...

Answer №1

let scrapDeliveryStatistics = [
  {
    supplierId: '0001055404',
    deliveredFrom: 'METALLCO AS',
    centerId: 'C45',
    materialId: 'TS0180',
  },
  {
    supplierId: '0001055404',
    deliveredFrom: 'METALLCO AS',
    centerId: 'C45',
    materialId: 'TS0085',
  },
  {
    supplierId: '0001055404',
    deliveredFrom: 'METALLCO AS',
    centerId: 'C45',
    materialId: 'TS0085',
  },
  {
    supplierId: '0001055404',
    deliveredFrom: 'METALLCO AS',
    centerId: 'C45',
    materialId: 'TS0180',
  },
  {
    supplierId: '0001055404',
    deliveredFrom: 'METALLCO AS',
    centerId: 'C45',
    materialId: 'TS0065',
  },
  {
    supplierId: '0001055404',
    deliveredFrom: 'METALLCO AS',
    centerId: 'C45',
    materialId: 'TS0065',
  },
];

const processedData = scrapDeliveryStatistics.reduce<
  Record<string, typeof statisticsOfScrapDeliveriesItems>
>((p, c) => {
  p[c.materialId] = p[c.materialId] || [];
  p[c.materialId].push(c);
  return p;
}, {});

console.log(processedData);

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

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

Update the value of a variable in a Django template by using the variable's content in

In my template, I am working with a variable key.links.self that contains a URL in the JSON output: https://ahostnamea.net:666/api/v1/ What I aim to achieve is to display only ahostnamea from this variable in the template. I am aware of how to trim char ...

When a TypeScript merged declaration composition is used with an extended target class, it fails to work properly

I have a TypeScript problem where I need to combine a class that has been extended with a few others. While searching for solutions, I came across an article outlining a pattern that I thought could be helpful: https://www.typescriptlang.org/docs/handbook ...

Discover the best method for retrieving or accessing data from an array using Angular

In my data processing task, I have two sets of information. The first set serves as the header data, providing the names of the columns to be displayed. The second set is the actual data source itself. My challenge lies in selecting only the data from th ...

Ways to retrieve class attributes in a child context

When trying to access the class properties (or methods) from another scope, I find myself having to store it in a local variable within the function scope. class MyClass { constructor(API) { this.API = API; this.property = 'value& ...

Utilizing UseRef in Typescript for an Idle Timer

Feeling frustrated with Typescript, everything seems unnecessarily complicated. Trying to follow a tutorial on react-idle-timer and encountering TypeScript compilation issues within minutes. The guides online suggest using when calling useRef with TypeS ...

Issue: Unable to locate a change supporting element '[object Object]' of the type 'object - Angular 7'

An angular service has been created for the specified purpose: CheckTicket(barcode, codEspec, diaHoraEspec):Observable<Ticket[]>{ //read ticket return this.http.get<Ticket[]>(`${this.checkticket_url}${barcode}?token=${this.token}&a ...

Challenges with Type Casting in TypeScript

Upon reviewing a specific piece of code, I noticed that it is not producing any compile time or run time errors even though it should: message: string // this variable is of type string -- Line 1 <br> abc: somedatatype // lets assume abc is of some ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Issue with Typescript typing for the onChange event

I defined my state as shown below: const [updatedStep, updateStepObj] = useState( panel === 'add' ? new Step() : { ...selectedStep } ); Additionally, I have elements like: <TextField ...

"Utilizing AJAX to set an array as a global variable

Struggling with storing data values from an AJAX response XML into a global array, and then attempting to call a function that removes specific elements from it. The issue lies in the fact that the array is not declared as global. Here's the current c ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

Is there a way for me to simultaneously run a typescript watch and start the server?

While working on my project in nodejs, I encountered an issue when trying to code and test APIs. It required running two separate consoles - one for executing typescript watch and another for running the server. Feeling frustrated by this process, I came ...

Angular example of Typeahead feature is sending a blank parameter to the backend server

I am currently trying to implement a similar functionality to the example provided at this link in my Angular frontend application. The goal is to send a GET request to my backend with the search parameter obtained from an input field. However, even thoug ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

An error is triggered by the EyeDropper API stating that 'EyeDropper' has not been defined

I am trying to utilize EyeDropper for an eyedropper function in my project that uses Vue2 + Ts. Here is the code snippet: <div v-if="haveEyeDropper" @click="handleClickPick" > <i class="iconfont icon-xiguan"> ...

Authenticating to Google APIs using Node.js within a lambda function: A step-by-step guide

I'm encountering an issue when trying to connect a Google sheet to an AWS Lambda function. While the code runs smoothly during local testing, upon deployment to the function, I receive an error message indicating that the credentials.json file cannot ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

The compatibility of return value types between the constructor signature and the call signature interface is not maintained when they are used together

I'm new to TypeScript and I'm struggling to figure out why I'm getting a type error in the code below. Can someone help me identify what's wrong? interface CallOrConstruct { new (value: string): Person (value: number): number } cla ...