美文网首页
ts数据分组方法

ts数据分组方法

作者: 背后_542d | 来源:发表于2023-07-06 16:11 被阅读0次
    interface GroupedData<T> {
      [key: string]: T[];
    }
    
    function groupBy<T>(array: T[], getGroupKey: (item: T) => string): GroupedData<T> {
      const groupedData: GroupedData<T> = {};
    
      for (const item of array) {
        const key = getGroupKey(item);
    
        if (!groupedData[key]) {
          groupedData[key] = [];
        }
    
        groupedData[key].push(item);
      }
    
      return groupedData;
    }
    
    interface Person {
      ID: string;
      Name: string;
      Gender: string;
      Birthday: string;
    }
    
    const data: Person[] = [
      {
        "ID": "1",
        "Name": "张三",
        "Gender": "男",
        "Birthday": "2020-03-24 00:00:00"
      },
      {
        "ID": "2",
        "Name": "李四",
        "Gender": "男",
        "Birthday": "2020-03-23 00:00:00"
      },
      {
        "ID": "3",
        "Name": "王五",
        "Gender": "男",
        "Birthday": "2020-03-23 00:00:00"
      },
      {
        "ID": "4",
        "Name": "赵六",
        "Gender": "男",
        "Birthday": "2020-03-28 00:00:00"
      },
      {
        "ID": "5",
        "Name": "田七",
        "Gender": "女",
        "Birthday": "2020-03-25 00:00:00"
      },
      {
        "ID": "6",
        "Name": "王五",
        "Gender": "男",
        "Birthday": "2020-03-22 00:00:00"
      }
    ];
    
    const groupedData = groupBy(data, (item) => item.Gender);
    const groupedData1 = groupBy(data, (item) => item.Gender+"_"+item.Birthday);
    
    
    console.log(groupedData);
    console.log(groupedData1);
    

    相关文章

      网友评论

          本文标题:ts数据分组方法

          本文链接:https://www.haomeiwen.com/subject/ptoludtx.html