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));
    
  • 相关阅读:
    python3图片转化成字符画
    ubuntu 18.04安装PIL(Python Imaging Library )
    Ubuntu 18.04安装钉钉
    django 使用iframe跨域请求
    django 自定义日志字段
    Ubuntu18.04下安装搜狗输入法(亲测有效)
    Nginx 配置指令手册
    js闭包Demo
    自己写了一个无缝滚动的插件(jQuery)
    写JQuery 插件 什么?你还不会写JQuery 插件
  • 原文地址:https://www.cnblogs.com/Leophen/p/13782591.html
Copyright © 2011-2022 走看看