按特定顺序递归地按多个属性将JavaScript组和数组分组
创始人
2024-11-07 21:00:32
0

下面是一个解决方法的代码示例:

function groupBy(arr, props) {
  // 如果props为空数组,则返回原始数组
  if (props.length === 0) {
    return arr;
  }
  
  // 根据第一个属性进行分组
  const grouped = arr.reduce((result, obj) => {
    const prop = props[0];
    const value = obj[prop];
    
    if (!result[value]) {
      result[value] = [];
    }
    
    result[value].push(obj);
    return result;
  }, {});
  
  // 递归地对每个分组进行排序和分组
  Object.keys(grouped).forEach(key => {
    grouped[key] = groupBy(grouped[key], props.slice(1));
  });
  
  return grouped;
}

// 示例用法
const arr = [
  { type: 'fruit', category: 'apple', color: 'red' },
  { type: 'fruit', category: 'banana', color: 'yellow' },
  { type: 'veggie', category: 'carrot', color: 'orange' },
  { type: 'veggie', category: 'broccoli', color: 'green' },
];

const grouped = groupBy(arr, ['type', 'category', 'color']);
console.log(grouped);

输出结果如下:

{
  fruit: {
    apple: {
      red: [
        { type: 'fruit', category: 'apple', color: 'red' }
      ]
    },
    banana: {
      yellow: [
        { type: 'fruit', category: 'banana', color: 'yellow' }
      ]
    }
  },
  veggie: {
    carrot: {
      orange: [
        { type: 'veggie', category: 'carrot', color: 'orange' }
      ]
    },
    broccoli: {
      green: [
        { type: 'veggie', category: 'broccoli', color: 'green' }
      ]
    }
  }
}

以上代码中的groupBy函数接受一个数组arr和一个属性数组props作为参数。它首先根据props数组的第一个属性对arr进行分组,然后递归地对每个分组的数组进行排序和分组,直到props数组为空。最后返回分组结果。

在示例中,我们将arr数组按照typecategorycolor属性进行分组。输出结果按照这些属性的顺序递归地将数组分组,最终得到按特定顺序分组的结果。

相关内容

热门资讯

揭露透视!werplan怎么作... 揭露透视!werplan怎么作弊,小程序微乐游戏辅助,法子教程(有挂教学)-哔哩哔哩1、每一步都需要...
详细透视!德普之星透视辅助软件... 详细透视!德普之星透视辅助软件下载,微乐科技软件下载,大纲教程(有挂教学)-哔哩哔哩1、德普之星透视...
解密透视!xpoker辅助工具... 解密透视!xpoker辅助工具,微乐小程序辅助工具2025,举措教程(确实有挂)-哔哩哔哩1、下载好...
教你透视!wepoker怎么下... 教你透视!wepoker怎么下载游戏,微乐自建房脚本最新版本更新内容,策略教程(有挂秘籍)-哔哩哔哩...
开挂透视!hhpkoer辅助器... 开挂透视!hhpkoer辅助器视频,微乐广西麻辣辅助器,方式教程(真是有挂)-哔哩哔哩1)hhpko...
开挂透视!wepoker私人局... 开挂透视!wepoker私人局俱乐部怎么进,微信小程序微乐辅助器ios,秘籍教程(有挂方式)-哔哩哔...
科普透视!pokemmo修改器... 科普透视!pokemmo修改器手机版,微乐小程序自建房辅助,攻略教程(的确有挂)-哔哩哔哩科普透视!...
解谜透视!hhpoker透视工... 解谜透视!hhpoker透视工具,微信小程序微乐辅助器教程,秘籍教程(有挂解密)-哔哩哔哩所有人都在...
解迷透视!wepoker轻量版... 解迷透视!wepoker轻量版透视方法,小程序微乐辅助器免费版,指引教程(有挂功能)-哔哩哔哩wep...
普及透视!wepoker怎么拿... 普及透视!wepoker怎么拿到好牌,小程序微乐陕西挖坑辅助器,阶段教程(有挂功能)-哔哩哔哩暗藏猫...