'Typescript: Classify objects by the attributes specified in them

[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 hope to reorganize an object array according to tokenxsymbol, tokenysymbol and feetier in the object array. The following is the method



Solution 1:[1]

const resultList = useMemo(() => {
    return originList.reduce((acc: any, e: Order) => {
        const key = e.tokenXSymbol + e.tokenYSymbol + String(e.feeTier);
        const r = acc.find((e: any) => e.key === key);
        r
            ? r.data.push(e)
            : acc.push({
                  key,
                  data: [e],
                  tokenXSymbol: e.tokenXSymbol,
                  tokenYSymbol: e.tokenYSymbol,
                  feeTier: e.feeTier,
              });
        return acc;
    }, []);
}, [originList]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 noneName