ts数据分组方法

2023-07-06  本文已影响0人  背后_542d
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);
上一篇 下一篇

猜你喜欢

热点阅读