array.groupBy in TypeScript

后端 未结 4 1875
盖世英雄少女心
盖世英雄少女心 2021-02-19 18:50

The basic array class has .map, .forEach, .filter, and .reduce, but .groupBy i noticably absent, preventing me f

4条回答
  •  时光取名叫无心
    2021-02-19 19:24

    You can use the following code to group stuff using Typescript.

    const groupBy = (list: T[], getKey: (item: T) => K) =>
      list.reduce((previous, currentItem) => {
        const group = getKey(currentItem);
        if (!previous[group]) previous[group] = [];
        previous[group].push(currentItem);
        return previous;
      }, {} as Record);
    

    So, if you have the following structure and array:

    type Person = {
      name: string;
      age: number;
    };
    
    const people: Person[] = [
      {
        name: "Kevin R",
        age: 25,
      },
      {
        name: "Susan S",
        age: 18,
      },
      {
        name: "Julia J",
        age: 18,
      },
      {
        name: "Sarah C",
        age: 25,
      },
    ];
    

    You can invoke it like:

    const results = groupBy(people, i => i.name);
    

    Which in this case, will give you an object with string keys, and Person[] values.

    There are a few key concepts here:

    1- You can use function to get the key, this way you can use TS infer capabilities to avoid having to type the generic every time you use the function.

    2- By using the K extends keyof any type constraint, you're telling TS that the key being used needs to be something that can be a key string | number | symbol, that way you can use the getKey function to convert Date objects into strings for example.

    3- Finally, you will be getting an object with keys of the type of the key, and values of the of the array type.

提交回复
热议问题