Search code examples
reactjstypescriptmultimap

React/Typescript multimap


I'm new to typescript and not able to figure out how to implement a multimap. I have the code as below. I need to iterate through the itemArray and store the Item according to date. I need to use the date as the key to the multimap. How to go about implementing this without using any external libraries?

interface Item {
    id: number;
    date: string;
}

interface Details{
    itemArray: Item[]
}

Solution

  • There are two ways to achieve this, Maps and indexable types.

    Indexable Types

    Indexable types are basic objects with their keys and values typed.:

    interface ItemMap {
        [key: string]: Item[];
    };
    

    Playground

    Maps

    Maps are a JS class that implements a hash map - This method is useful when indexing by non-string/number types.

    type ItemMap = Map<string, Item[]>
    

    Playground