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));
    
  • 相关阅读:
    StratifiedKFold和KFold的区别(几种常见的交叉验证)
    剑指offer:用栈来建立队列
    剑指offer:斐波那契数列
    树状数组 gcd 查询 Different GCD Subarray Query
    Loadrunner的使用
    Loadrunner的使用
    MySQL Windows 环境安装
    RobotFrameWork 自动化环境搭建(基于 python3.6)
    MySQL Linux 环境安装
    【读书笔记】状态模式代码C#
  • 原文地址:https://www.cnblogs.com/Leophen/p/13782591.html
Copyright © 2011-2022 走看看