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

如何用JavaScript按月份过滤dd / MM / yyyy格式日期的数组?

按月份精准过滤数组的解决方案

给定数组:

const relTotal = [
  [11111,'15 / 05 / 2024','11:11hs','teste de a3','admin'],
  [12541,'03 / 06 / 2024','11:28hs','teste de a3','admin'],
  [151515,'22 / 03 / 2024','15:15hs','testes','testetes'],
  [151515,'22 / 05 / 2024','15:15hs','testes','testetes']
];

日期字段格式固定为dd / MM / yyyy(含空格),需求是仅根据月份MM过滤数组。之前使用includes("03")会误匹配所有包含"03"的内容(比如日期中的日、ID等),无法精准过滤月份。

正确实现方法

方法1:拆分日期字符串提取月份

利用固定日期格式的结构,拆分字符串后直接取月份部分对比:

const targetMonth = "03";
const retFilter = relTotal.filter(item => {
  // 拆分日期为 ['dd', '/', 'MM', '/', 'yyyy']
  const dateSegments = item[1].split(' ');
  // 索引2对应的就是月份部分
  return dateSegments[2] === targetMonth;
});
console.log(retFilter);

该方法直接定位日期字段的月份位置,完全避免误匹配其他字段。

方法2:正则精准匹配月份

用正则表达式匹配日期中特定位置的月份片段:

const targetMonth = "03";
// 匹配 " / 03 /" 格式的月份片段
const monthPattern = new RegExp(`\\/ ${targetMonth} \\/`);
const retFilter = relTotal.filter(item => monthPattern.test(item[1]));
console.log(retFilter);

正则会精准匹配日期字符串中被/包裹的月份,确保只匹配日期里的月份部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:33:11