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

如何在Angular/ES6中按月份过滤数组并获取最大Date值?

按月份过滤数组并获取最大日期对象

问题背景

我有一个包含日期值的对象数组,需要根据selectedDate按月份过滤数组,并从中获取日期最大的对象。目前已通过过滤得到符合月份条件的元素,现需用ES6或Angular兼容的方式完成后续取值。

原代码示例

let selectedDate = new Date();
let array = [{
    "date": "2022-08-30T23:00:00Z",
    "value": "4.0"
  },
  {
    "date": "2022-08-28T23:00:00Z",
    "value": "8.0"
  },
  {
    "date": "2022-08-25T23:00:00Z",
    "value": "2.0"
  },
  {
    "date": "2022-07-25T23:00:00Z",
    "value": "2.0"
  }
];

let x = array.filter(d =>
  new Date(d.date).getMonth() === selectedDate.getMonth() - 1
)
console.log(x)

解决方案

1. ES6原生实现(推荐)

在过滤数组的基础上,使用reduce方法遍历比较,找出日期最大的对象。建议同时校验年份,避免跨年度同月份数据被误匹配:

let selectedDate = new Date();
let array = [{
    "date": "2022-08-30T23:00:00Z",
    "value": "4.0"
  },
  {
    "date": "2022-08-28T23:00:00Z",
    "value": "8.0"
  },
  {
    "date": "2022-08-25T23:00:00Z",
    "value": "2.0"
  },
  {
    "date": "2022-07-25T23:00:00Z",
    "value": "2.0"
  }
];

// 过滤指定月份(含年份校验)的元素
const filteredArray = array.filter(item => {
  const itemDate = new Date(item.date);
  return itemDate.getMonth() === selectedDate.getMonth() - 1 
         && itemDate.getFullYear() === selectedDate.getFullYear();
});

// 从过滤结果中获取日期最大的对象
const maxDateItem = filteredArray.length 
  ? filteredArray.reduce((prev, curr) => {
      return new Date(prev.date) > new Date(curr.date) ? prev : curr;
    }, filteredArray[0])
  : null; // 处理过滤结果为空的情况

console.log(maxDateItem);

2. Angular中结合RxJS的实现(适用于Observable数组)

如果你的数组是RxJS Observable类型(比如从HTTP请求获取),可以通过管道操作符组合过滤和取值逻辑:

import { map, filter } from 'rxjs/operators';

// 假设array$是Observable类型的数组数据源
const array$ = /* 你的Observable数据源 */;

array$.pipe(
  // 过滤指定月份和年份的元素
  map(arr => arr.filter(item => {
    const itemDate = new Date(item.date);
    return itemDate.getMonth() === selectedDate.getMonth() - 1 
           && itemDate.getFullYear() === selectedDate.getFullYear();
  })),
  // 提取日期最大的对象
  map(filteredArr => filteredArr.length 
    ? filteredArr.reduce((prev, curr) => new Date(prev.date) > new Date(curr.date) ? prev : curr, filteredArr[0])
    : null)
).subscribe(maxItem => {
  console.log(maxItem);
  // 在这里处理结果,比如赋值给组件变量
});

期望输出

{
  "date": "2022-08-30T23:00:00Z",
  "value": "4.0"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:24:26