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

Angular:将数组中相同日期的元素合并为分组对象并展示

Angular 按日期分组展示数组数据

要实现按日期分组展示的效果,你可以分两步处理:先在组件逻辑里把原数组按日期分组,再修改模板渲染分组后的数据。

1. 在组件中处理数组分组

在你的 Angular 组件类里,用 reduce 方法把原数组按 date 字段分组,生成以日期为键、对应姓名数组为值的对象:

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

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  array = [{
      name: 'Camilla',
      date: '00.08.1990'
    },
    {
      name: 'John',
      date: '10.06.2022'
    },
    {
      name: 'Paul',
      date: '10.06.2022'
    }];

  // 分组后的数据结构:{日期: [姓名1, 姓名2...]}
  groupedByDate = this.array.reduce((groups, item) => {
    const date = item.date;
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(item.name);
    return groups;
  }, {} as {[key: string]: string[]});
}

2. 修改HTML模板渲染分组数据

把原来的单层 *ngFor 改成嵌套结构,先遍历每个日期分组,再渲染该日期下的所有姓名:

<div>分组展示:
  <!-- 遍历所有日期分组 -->
  <div *ngFor="let dateGroup of groupedByDate | keyvalue">
    <div style="font-weight: bold; margin-top: 10px;">{{ dateGroup.key }}</div>
    <!-- 遍历当前日期下的姓名列表 -->
    <div style="border-style: solid; margin-left: 10px;" *ngFor="let name of dateGroup.value">
      {{ name }}
    </div>
  </div>
</div>

这样就能实现同一日期下的姓名归为一组展示的效果,日期作为组标题,下方列出对应所有姓名。

内容的提问来源于stack exchange,提问作者Martin Delus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:40:39