function listFilter(selectday, array) {
// 获取当前日期 年月日
function getNowFormatDate() {
const date = new Date();
const year = date.getFullYear(); // 获取完整的年份(4位)
let month = date.getMonth() + 1; // 获取当前月份(0-11,0代表1月)
let strDate = date.getDate(); // 获取当前日(1-31)
if (month < 10) month = `0${month}`; // 如果月份是个位数,在前面补0
if (strDate < 10) strDate = `0${strDate}`; // 如果日是个位数,在前面补0
const res = `${year}-${month}-${strDate}`;
return res;
}
const nowday = getNowFormatDate();
const newArr = array.filter((item) => {
return (
Date.parse(item.date) >= Date.parse(nowday) - selectday * 24 * 60 * 60 * 1000
);
});
return newArr
}
const list=[
{date: "2023-04-11", region: "学习", hours: 1, desc: "", recordId: "922c6dd0b73b9"},
{date: "2023-05-01", region: "工作", hours: 0.5, desc: "", recordId: "bb22c2c57e639"},
{date: "2023-05-05", region: "工作", hours: 1, desc: "", recordId: "c1550fcfb5674"},
{date: "2023-05-07", region: "工作", hours: 5, desc: "", recordId: "18c8903c6cc19"},
{date: "2023-04-04", region: "学习", hours: 3.5, desc: "", recordId: "610761b1e7f09"},
{date: "2022-04-29", region: "运动", hours: 4, desc: "", recordId: "629bf49e61336"},
{date: "2023-04-03", region: "学习", hours: 1.5, desc: "", recordId: "e137a23954958"},
{date: "2023-05-07", region: "娱乐", hours: 0.5, desc: "", recordId: "0020ce569c222"},
{date: "2023-05-11", region: "运动", hours: 0.5, desc: "", recordId: "bec99066fa487"}
]
// 筛选出过去7天的数据
console.log(listFilter(7,list))
/* 结果[
{
date: '2023-05-05',
region: '工作',
hours: 1,
desc: '',
recordId: 'c1550fcfb5674'
},
{
date: '2023-05-07',
region: '工作',
hours: 5,
desc: '',
recordId: '18c8903c6cc19'
},
{
date: '2023-05-07',
region: '娱乐',
hours: 0.5,
desc: '',
recordId: '0020ce569c222'
},
{
date: '2023-05-11',
region: '运动',
hours: 0.5,
desc: '',
recordId: 'bec99066fa487'
}
]
*/
筛选数组中时间为最近几天的数据
于 2023-05-11 15:57:16 首次发布
该代码段定义了一个名为listFilter的函数,它接受两个参数:selectday和array。函数首先获取当前日期,然后过滤array中的对象,只保留那些日期在最近selectday天内的项。提供的数据列表是一个包含日期、活动类型等信息的对象数组。示例调用显示了如何筛选过去7天的记录。
摘要由CSDN通过智能技术生成