如何用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
相关产品推荐
相关产品推荐

