根据日期区间在JavaScript数组对象中匹配对应元素的实现
实现日期区间匹配的JavaScript函数
原始数据数组
const array = [ { "state": "AK", "classCode": "ISO_11204", "territory": "1", "territoryLabel": "001 - Entire State", "finalPremOps": 0.27, "finalPCo": 0.6, "startDate": '1/1/2020', "endDate": '12/31/2020' }, { "state": "AK", "classCode": "ISO_11204", "territory": "1", "territoryLabel": "001 - Entire State", "finalPremOps": 0.27, "finalPCo": 0.6, "startDate": '1/1/2021', "endDate": '12/31/2021' }, { "state": "AK", "classCode": "ISO_11204", "territory": "1", "territoryLabel": "001 - Entire State", "finalPremOps": 0.27, "finalPCo": 0.6, "startDate": '1/1/2022', "endDate": null }, ]
需求说明
实现一个函数,根据传入的当前日期,从上述数组中查找处于startDate与endDate区间内的元素,匹配规则如下:
- 若当前日期晚于2022年1月1日,返回最后一个元素;
- 若当前日期为2021年1月2日,返回第二个元素;
- 若当前日期为2020年1月2日,返回第一个元素。
实现代码
function findMatchingElement(currentDateStr) { // 将输入日期转为可比较的Date对象 const currentDate = new Date(currentDateStr); // 遍历数组筛选符合区间条件的元素 return array.find(item => { const start = new Date(item.startDate); // endDate为null时,视为无截止日期,用极大值替代 const end = item.endDate ? new Date(item.endDate) : new Date('9999-12-31'); // 判断当前日期是否处于区间内(包含首尾日期) return currentDate >= start && currentDate <= end; }); }
测试示例
// 测试:当前日期晚于2022年1月1日 console.log(findMatchingElement('1/2/2022')); // 返回数组最后一个元素 // 测试:当前日期为2021年1月2日 console.log(findMatchingElement('1/2/2021')); // 返回数组第二个元素 // 测试:当前日期为2020年1月2日 console.log(findMatchingElement('1/2/2020')); // 返回数组第一个元素
内容的提问来源于stack exchange,提问作者Mohamed El Mahallawy
相关产品推荐
相关产品推荐

