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

Authentication Redirect Failure when using Passport to an absolute URL

I am looking to redirect the user to a different URL with the code/token received after logging into Facebook using Passport in Express.js. app.get('/auth/facebook/callback', function (req, res, next) { var authenticator = passport.authentic ...

TypeScript functions with Generic Constraints return specific values rather than just types

function createGenericCoordinates<Type extends number | string>( x: Type, y: Type ) { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); // Error (TS2322) // Type 3 is not assignable to type 1 | 2 genericCoordinates ...

Using Angular 4 for HTML 5 Drag and Drop functionality

I have been working on integrating native HTML 5 drag & drop functionality into my angular application. While I have successfully implemented the drag and dragOver events, I am facing an issue with the drop event not firing as expected. Here is the snipp ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...

Exploring Typescript: Combining types (rather than intersecting them)

Let's analyze the scenario below type MergeFn = <K1 extends string, V1, K2 extends string, V2>( k1: K1, v1: V1, k2: K2, v2: V2 ) => ??? let mergeFn: MergeFn // actual implementation doesn't matter for this question What should b ...

"Exploring the power of Angular 16 coupled with Firebase 9 for seamless file

Recently, I've been facing some challenges with my Angular 16 app that uses Firebase 9 and angular/fire 7. Specifically, I've been struggling to implement a simple file upload feature to Firebase storage. Despite spending the last couple of days ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

Setting the dispatch type in Redux using Typescript

I'm new to typescript and I'm trying to figure out what type should be assigned to the dispatch function. Currently, I am using 'any', but is there a way to map all actions to it? Here's how my code looks like: interface PropType ...

Resolving the non-null assertion error in TypeScript and React: A step-by-step guide

My code snippet is as follows: type ItemProps = { status?: string; } <Items status={status!} /> // encountering an error with a warning about forbidden non-null assertion // @typescript-eslint/no-non- ...

NGXS Alert: Unable to resolve parameters for TranslationEditorState: (?)

I'm currently implementing NGXS for state management within my Angular 9 application. I've encountered a specific issue where any attempt at dependency injection in one of the state classes results in an error message stating "Error: Can't r ...

Storing data from a service into an array in Angular: Best practices

I have a service that provides getter and setter methods, returning id: number and title: String values from my dialog component. I am trying to save these responses into my data array but struggling to achieve it. For instance: 0: {id: 0, title: &qu ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

Tips for fixing TypeScript compiler error TS2339: Issue with accessing 'errorValue' property in Angular 5 project

Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to e ...

Retrieve the current step index in Angular Material Design Stepper

In my endeavors to retrieve the selected step within a component utilizing Angular Material Design stepper, I am encountering some issues. My current approach involves using the selectedIndex property, but it consistently returns "1" instead of the desire ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

How can we automate the process of assigning the hash(#) in Angular?

Is it possible to automatically assign a unique hash(#) to elements inside an ngFor loop? <div *ngFor="let item of itemsArray; index as i"> <h3 #[item][i]> {{ item }} </h3> </div> I would like the outp ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Looking to filter JSON data with Vuejs?

I am trying to search through this JSON array for a specific key: track_order The data I receive from the server is stored in the orders variable: "records": [ { "phone": "09********8", "fullName": "******", ...

Assigning a price to a list of pizza options within a dropdown menu

//The goal is to assign a numerical price to each pizza in the array. We must maintain the structure of the array within the select form. Next, we need to display it in another PHP file, how do we retrieve the values? <fieldset> ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...