You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular或JavaScript中统计分组数组的各分组长度?

嘿,这个需求超常见的,我给你俩实用的实现方案,保证能让你轻松拿到每个分组的长度~

实现分组长度统计的两种方案

方案一:构建完整分组对象(保留分组内的所有项)

如果你不仅需要分组长度,还可能后续用到分组里的具体数据,那可以用Array.reduce()把原数组转换成一个以分组名为键、对应分组数组为值的对象:

const array = [ 
  { name: 'hello 1', checked: true, color:'#1ac3ec', group:'first category' }, 
  { name: 'hello 2', checked: true, color:'#7dc55c', group:'first category' }, 
  { name: 'hello 3', checked: true, color:'#005073', group:'second category' },
  { name: 'hello 4', checked: true, color:'#fbb330', group:'second category' } 
];

// 用reduce构建分组对象
const groupedArray = array.reduce((acc, item) => {
  // 若当前分组未初始化,先创建空数组
  if (!acc[item.group]) {
    acc[item.group] = [];
  }
  // 将当前项加入对应分组
  acc[item.group].push(item);
  return acc;
}, {});

这样处理后,你就能完全按照想要的方式获取长度了:

console.log(groupedArray['first category'].length); // 输出 2
console.log(groupedArray['second category'].length); // 输出 2

方案二:直接统计分组长度(更高效,适合只需要长度的场景)

如果只关心分组的长度,不需要保留分组内的具体数据,那可以在reduce里直接累加计数,这样更节省内存:

const array = [ /* 你的原数组 */ ];

// 直接统计每个分组的长度
const groupLengths = array.reduce((acc, item) => {
  // 若分组不存在则初始化为0,然后加1;否则直接加1
  acc[item.group] = (acc[item.group] || 0) + 1;
  return acc;
}, {});

此时直接通过分组名就能拿到长度:

console.log(groupLengths['first category']); // 输出 2
console.log(groupLengths['second category']); // 输出 2

Angular环境中的使用示例

Angular本质上基于TypeScript/JavaScript,上述逻辑完全适用。你可以把这段代码放在组件的初始化逻辑里,比如:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent implements OnInit {
  // 定义你的数组
  array = [ 
    { name: 'hello 1', checked: true, color:'#1ac3ec', group:'first category' }, 
    { name: 'hello 2', checked: true, color:'#7dc55c', group:'first category' }, 
    { name: 'hello 3', checked: true, color:'#005073', group:'second category' },
    { name: 'hello 4', checked: true, color:'#fbb330', group:'second category' } 
  ];

  // 存储分组长度的对象
  groupLengths: { [key: string]: number } = {};

  ngOnInit(): void {
    // 初始化分组长度统计
    this.groupLengths = this.array.reduce((acc, item) => {
      acc[item.group] = (acc[item.group] || 0) + 1;
      return acc;
    }, {});
  }

  // 也可以封装一个方法来获取指定分组的长度
  getGroupLength(groupName: string): number {
    return this.groupLengths[groupName] || 0;
  }
}

在模板里也能直接使用:

<p>First category length: {{ groupLengths['first category'] }}</p>
<p>Second category length: {{ getGroupLength('second category') }}</p>

内容的提问来源于stack exchange,提问作者Manish Salunke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:13:10