筛选数组中时间为最近几天的数据

该代码段定义了一个名为listFilter的函数,它接受两个参数:selectday和array。函数首先获取当前日期,然后过滤array中的对象,只保留那些日期在最近selectday天内的项。提供的数据列表是一个包含日期、活动类型等信息的对象数组。示例调用显示了如何筛选过去7天的记录。
摘要由CSDN通过智能技术生成
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'
  }
]
*/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值