Function: groupByKey()
Gala Launchpad SDK 9.0.0-rc.5 / index / groupByKey
Function: groupByKey()
groupByKey<
T,K>(items,keyFn):Map<K,T[]>
Defined in: packages/launchpad-sdk/dist/utils/array-helpers.d.ts:114
Group array items by a computed key into a Map
Provides a type-safe alternative to object-based grouping, supporting any key type (strings, numbers, objects, etc.)
Replaces the common pattern:
const groups = new Map<K, T[]>();
items.forEach((item) => {
const key = computeKey(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(item);
});
Type Parameters
T
T
The type of items in the array
K
K
The type of the grouping key
Parameters
items
T[]
Array of items to group
keyFn
(item) => K
Function that computes the grouping key for each item
Returns
Map<K, T[]>
Map with keys mapping to arrays of grouped items
Examples
// Group positions by token pair
interface LiquidityPosition {
token0: string;
token1: string;
liquidity: string;
}
const positions: LiquidityPosition[] = [
{ token0: 'GALA', token1: 'GUSDC', liquidity: '1000' },
{ token0: 'GALA', token1: 'GWETH', liquidity: '500' },
{ token0: 'GALA', token1: 'GUSDC', liquidity: '2000' },
];
const grouped = groupByKey(
positions,
(pos) => `${pos.token0}/${pos.token1}`
);
// Result: Map {
// 'GALA/GUSDC' => [{ token0: 'GALA', token1: 'GUSDC', liquidity: '1000' }, ...],
// 'GALA/GWETH' => [{ token0: 'GALA', token1: 'GWETH', liquidity: '500' }]
// }
grouped.get('GALA/GUSDC'); // Array of both GALA/GUSDC positions
// Group trades by status
interface Trade {
id: string;
status: 'pending' | 'completed' | 'failed';
amount: number;
}
const trades: Trade[] = [...];
const byStatus = groupByKey(trades, (trade) => trade.status);
const pending = byStatus.get('pending') || [];
const completed = byStatus.get('completed') || [];
const failed = byStatus.get('failed') || [];
// Group by numeric key
interface DataPoint {
timestamp: number;
value: number;
}
const data: DataPoint[] = [...];
// Group by hour (rounded timestamp)
const byHour = groupByKey(
data,
(point) => Math.floor(point.timestamp / (60 * 60 * 1000))
);
// Group with object key (requires key to be serializable)
interface Event {
chainId: number;
contractAddress: string;
data: unknown;
}
const events: Event[] = [...];
// Group by contract on each chain
const byChainContract = groupByKey(
events,
(event) => `${event.chainId}:${event.contractAddress}`
);
Remarks
- Uses
Mapfor better type safety and support for non-string keys - The key function is called once per item (O(n) complexity)
- Maintains insertion order of keys
- Suitable for large datasets due to Map's efficiency
- Key equality determined by
===comparison (or custom equals for objects)