Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: "0x**********" tokenYSymbol: "aaa" 1: {orderId: '11', tokenXSymbol: 'USDC', tokenYSymbol: 'USDT', tokenXAddr: '0x**********', tokenYAddr: '0x**********', …} 2: {orderId: '4', tokenXSymbol: 'USDT', tokenYSymbol: 'USDC', tokenXAddr: '0x**********', tokenYAddr: '0x**********', …}

expect array: 0: {key: 'USDTUSDC0.3', data: Array(2), tokenXSymbol: 'USDT', tokenYSymbol: 'USDC', feeTier: 0.3} 1: {key: 'USDTUSDC0.05', data: Array(1), tokenXSymbol: 'USDT', tokenYSymbol: 'USDC', feeTier: 0.05}

I aim to rearrange an object array based on tokenxsymbol, tokenysymbol, and feetier within the object array. The approach is outlined below.

Answer №1

const generatedList = useMemo(() => {
    return originalList.reduce((accumulator: any, item: Order) => {
        const keyIdentifier = item.tokenXSymbol + item.tokenYSymbol + String(item.feeTier);
        const result = accumulator.find((element: any) => element.key === keyIdentifier);
        result
            ? result.data.push(item)
            : accumulator.push({
                  key: keyIdentifier,
                  data: [item],
                  tokenXSymbol: item.tokenXSymbol,
                  tokenYSymbol: item.tokenYSymbol,
                  feeTier: item.feeTier,
              });
        return accumulator;
    }, []);
}, [originalList]);

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

Guide to implementing scheduled tasks in a Node.js API using Express

Currently, my Node API has multiple endpoints, and while they work well for the most part, there is one endpoint that struggles with processing large requests taking up to 1 hour. To handle this, I am considering implementing a system where instead of wait ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Trouble with a third-party library component not functioning properly on the server side in a Next.js environment

I've encountered a puzzling issue lately in my work. Recently, I started using the new NextJS v13 with React server components. I'm integrating it into a project that depends on a small private third-party library I created and shared among mul ...

Strategies for evaluating a Promise-returning imported function in Jest

I am currently facing an issue with a simple function that I need to write a test for in order to meet the coverage threshold. import { lambdaPromise } from '@helpers'; export const main = async event => lambdaPromise(event, findUsers); The ...

Ways to activate subscriptions in type-graphql?

I'm encountering an issue with setting up subscriptions in my Apollo Server project using Express. Despite following all the steps outlined in the documentation [https://typegraphql.com/docs/subscriptions.html], I can't seem to get it working. In ...

Error TS2322: The specified type 'Element' cannot be assigned to the type 'boolean'

I'm just beginning to explore TypeScript and I ran into an issue while trying to type my constant dialogFuncMap. I received an error (listed in the comments below). Why am I getting this error if the type of state is boolean? And how can I resolve it ...

Changing the color of an Angular <div> element with scripting

I am currently working on an Angular 6 project and I need to change the colors of a div tag from a script after a click function. However, I also need to change it back to transparent. When I click on the "Inheritance" option, the background color of the ...

Can you explain the significance of <this> within TypeScript generics?

Our application employs express along with TypeScript. While exploring their type definitions, I stumbled upon the following snippet and I'm curious about its meaning: export interface IRouter extends RequestHandler { all: IRouterMatcher<this& ...

c: resize memory allocated to a struct member

#define DEFAULT_SIZE 100 struct my_struct { struct some_struct *ptr; size_t len; char buf[0]; }; struct my_struct *s; s = malloc(sizeof *s + DEFAULT_SIZE); ... Suppose I want to increase the memory allocated for buf. Do I have to create a new ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .p ...

Assembly of Components

As someone new to angular, I am currently in the process of building an angular2 application. My goal is to dynamically create a series of DOM components using the data provided below: // Class construct with properties sorted alphabetically export class ...

What method can be used to specify a function of any signature that returns a particular type in programming?

I am looking to define a unique type that must be a function which, when executed, will always produce an object containing the property type: string. The input parameters for this function are of no concern. For instance: foo(1, 'bar'); // res ...

"CanDeactivate Implementation Failure: Why isn't the Generic Function Being Called

I am currently working on implementing a guard to prevent users from navigating to the login page once they have authenticated themselves. This guard should apply to all page components in my app except for the login page. Below is the code snippet I am u ...

"Implementing self-referencing mongoose models in Typescript: A step-by-step guide

I have a model: const message = new mongoose.Schema({ id: { type: ObjectId, required: true }, text: { type: String }, replies: [message] }); Looking to create a document structure like this: { "id": 1, "text": "Main Message", "replies": [ ...

Retrieve all information from the "orders" array within the User collection in MongoDB where the email is equal to [email protected]

Struggling with what may seem like a simple task, I am having difficulty. I am trying to search for a user using their email provided in req.params. Once the user is found, my goal is to retrieve all of their orders without any filtering. Currently, my r ...

"Experience the seamless navigation features of React Navigation V6 in conjunction with

Hello there, I've been experimenting with react-navigation 6 in an attempt to show a modal with presentation: "modal" as instructed on the documentation. However, I'm facing an issue where the modal is not displaying correctly and appears like a ...

Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects. Here is the dataset that I want to organize alphabetically based on the 'state' field values: stat ...

Arranged array through the process of quicksort

Hey there, I'm currently working on a project that involves creating an array of 10 random integers and sorting them using quicksort. However, I've encountered a problem when trying to scale this up to 1,000,000 random integers. It seems like the ...

Error encountered while trying to send an array list using the $.ajax function in jQuery

My web API expects JSON data in the following format (input parameter) { "districtID": "string", "legendIDs": ["string","string"] } Below is the JavaScript code I am using to build the request: var cityDistrictId = 'fb7b7ecd-f8df-4591-89de-0c9d ...