首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何对数组obj进行分组?

对数组obj进行分组可以使用不同的方法,以下是几种常见的分组方法:

  1. 使用普通的循环遍历:通过遍历数组obj的每个元素,根据特定的条件将元素分组到不同的数组中。
  2. 使用JavaScript的reduce()方法:reduce()方法可以将数组元素按照指定的条件进行分组。通过定义一个累加器函数和初始值,可以对数组中的每个元素进行分组操作。
  3. 使用ES6中的Map对象:Map对象是一种键值对的集合,其中的键可以是任意类型。可以利用Map对象的特性将数组元素按照特定的条件进行分组。

以下是对每种方法的详细说明:

  1. 使用普通的循环遍历:
代码语言:txt
复制
function groupBy(array, key) {
  const groups = {};
  array.forEach(item => {
    const group = item[key];
    if (!groups[group]) {
      groups[group] = [];
    }
    groups[group].push(item);
  });
  return groups;
}

const obj = [
  { id: 1, name: 'John', group: 'A' },
  { id: 2, name: 'Jane', group: 'B' },
  { id: 3, name: 'Bob', group: 'A' },
  { id: 4, name: 'Alice', group: 'B' }
];

const groupedObj = groupBy(obj, 'group');
console.log(groupedObj);

输出结果为:

代码语言:txt
复制
{
  A: [
    { id: 1, name: 'John', group: 'A' },
    { id: 3, name: 'Bob', group: 'A' }
  ],
  B: [
    { id: 2, name: 'Jane', group: 'B' },
    { id: 4, name: 'Alice', group: 'B' }
  ]
}
  1. 使用JavaScript的reduce()方法:
代码语言:txt
复制
function groupBy(array, key) {
  return array.reduce((result, currentValue) => {
    const group = currentValue[key];
    (result[group] = result[group] || []).push(currentValue);
    return result;
  }, {});
}

const obj = [
  { id: 1, name: 'John', group: 'A' },
  { id: 2, name: 'Jane', group: 'B' },
  { id: 3, name: 'Bob', group: 'A' },
  { id: 4, name: 'Alice', group: 'B' }
];

const groupedObj = groupBy(obj, 'group');
console.log(groupedObj);

输出结果与上述方法相同。

  1. 使用ES6中的Map对象:
代码语言:txt
复制
function groupBy(array, key) {
  const groups = new Map();
  array.forEach(item => {
    const group = item[key];
    if (!groups.has(group)) {
      groups.set(group, []);
    }
    groups.get(group).push(item);
  });
  return Object.fromEntries(groups);
}

const obj = [
  { id: 1, name: 'John', group: 'A' },
  { id: 2, name: 'Jane', group: 'B' },
  { id: 3, name: 'Bob', group: 'A' },
  { id: 4, name: 'Alice', group: 'B' }
];

const groupedObj = groupBy(obj, 'group');
console.log(groupedObj);

输出结果与上述方法相同。

以上是对数组obj进行分组的几种常见方法。根据实际需求和情况选择合适的方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

21分46秒

如何对AppStore上面的App进行分析

1分11秒

如何使用RFID对固定资产进行盘点

2分48秒

管理中心丨如何对用户进行权限管理?

45秒

管理中心丨如何对项目进行管理?

50秒

管理中心丨如何对资源进行管理?

4分39秒

看我如何使用Python对行程码与健康码图片文字进行识别统计

3分23秒

2.12.使用分段筛的最长素数子数组

2分23秒

【视频】使用Geobuilding软件将geojson或shapefile转换为3D三维城市模型文件

22分0秒

产业安全专家谈 | 企业如何进行高效合规的专有云安全管理?

14分29秒

NVIDIA英伟达Tensor Core深度剖析(下)【AI芯片】GPU架构06

30分53秒

【玩转腾讯云】腾讯云宝塔Linux面板安装及安全设置

14分19秒

Eclipse用法专题-01-简介下载与安装

领券