zoukankan      html  css  js  c++  java
  • JS/TS 对数组中的对象按相同值进行分组

    举个例子:对以下数组按 lastName 的值进行分组分类

    const listData = [
      { firstName: "Rick", lastName: "Sanchez", size: 18 },
      { firstName: "Morty", lastName: "Smith", size: 6 },
      { firstName: "Jerry", lastName: "Smith", size: 3 },
      { firstName: "Beth", lastName: "Smith", size: 0 },
      { firstName: "Summer", lastName: "Smith", size: 0 },
      { firstName: "Rick", lastName: "Sanchez", size: 18 },
      { firstName: "Morty", lastName: "Smith", size: 6 },
    ];
    

    分组前:

    分组后:

    一、普通写法

    const sortClass = (sortData) => {
      const groupBy = (array, f) => {
        let groups = {};
        array.forEach((o) => {
          let group = JSON.stringify(f(o));
          groups[group] = groups[group] || [];
          groups[group].push(o);
        });
        return Object.keys(groups).map((group) => {
          return groups[group];
        });
      };
      const sorted = groupBy(sortData, (item) => {
        return item.lastName; // 返回需要分组的对象
      });
      return sorted;
    };
    
    // 分组前
    console.log(listData);
    // 分组后
    console.log(sortClass(listData));
    

    二、TS 写法

    const sortClass = (sortData: ListDataItem[]) => {
      const groupBy = (array: ListDataItem[], f: Function) => {
        const groups: {
          [key: string]: ListDataItem[],
        } = {};
        array.forEach((item) => {
          const group = JSON.stringify(f(item));
          groups[group] = groups[group] || [];
          groups[group].push(item);
        });
        return Object.keys(groups).map((group) => {
          return groups[group];
        });
      };
      const sorted = groupBy(sortData, (item: ListDataItem) => {
        return item.lastName;
      });
      return sorted;
    };
    
    // 分组前
    console.log(listData);
    // 分组后
    console.log(sortClass(listData));
    
  • 相关阅读:
    codeforces 673D D. Bear and Two Paths(构造)
    codeforces 673C C. Bear and Colors(暴力)
    codeforces 673B B. Problems for Round(模拟)
    codeforces 673A A. Bear and Game(水题)
    hdu-3555 Bomb(数位dp)
    西交校赛 I. GZP and CS(数位dp)
    西交校赛 F. GZP and Poker
    删除目录下包含“2018” 关键字文件
    CSV转成Excel格式
    解决字符sqlplus 乱码
  • 原文地址:https://www.cnblogs.com/Leophen/p/13782591.html
Copyright © 2011-2022 走看看