繁体   English   中英

如何根据最新日期过滤/减少数据

[英]How to filter/reduce the data based on the latest date

data = {
 start: 1,
 data: [
  {
   name: 'Juan',
   date: '2020-01-19
  },
  {
   name: 'Carlo',
   date: '2020-03-01
  },
  {
   name: 'Dela',
   date: '2020-03-01
  },
  {
   name: 'Cruz',
   date: '2021-04-01
  }
 ],
 totalRecords: 19
}

我正在尝试将数据过滤到最新日期2020-04-01

我尝试的是这样的:

response['data']['data'] = response['data']['data'].filter(item => {
           return item['date'] > '2020-04-01';
         });

但它不起作用。

预期的 output应该是这样的

data = {
 start: 1,
 data: [
  {
   name: 'Cruz',
   date: '2021-04-01
  }
 ],
 totalRecords: 19
}

您需要将日期字符串转换为Date对象。

 const checkDate = new Date('2020-04-01') const response = { start: 1, data: [ { name: 'Juan', date: '2020-01-19' }, { name: 'Carlo', date: '2020-03-01' }, { name: 'Dela', date: '2020-03-01' }, { name: 'Cruz', date: '2021-04-01' } ], totalRecords: 19 } response.data = response.data.filter(({date}) => new Date(date) > checkDate) console.log(response)

其他答案存在一些问题(在性能、预期输出方面)。

  1. 您不应该使用sort ,因为time complexity至少需要O(nlogn)
  2. 使用filter将返回多个lastItem

==>所以你可以像这样使用Array#reduce (时间复杂度仅为O(n) )。

 const comparedDate = new Date('2020-04-01') const response = { start: 1, data:[{name:'Juan',date:'2020-01-19'},{name:'Carlo',date:'2020-03-01'},{name:'Dela',date:'2020-03-01'},{name:'Cruz',date:'2021-04-01'}], totalRecords:19}; const lastData = response.data.reduce((acc, curr) => { if(new Date(curr.date) > comparedDate) acc = curr; return acc; }, response.data[0]); console.log(lastData);

如果您想产生多个项目 <= 2020-04-01 ,您可以这样做

 const comparedDate = new Date('2020-04-01') const response = { start: 1, data:[{name:'Juan',date:'2020-01-19'},{name:'Carlo',date:'2020-03-01'},{name:'Dela',date:'2020-03-01'},{name:'Cruz',date:'2021-04-01'}], totalRecords:19}; response.data = response.data.reduce((acc, curr) => { if(new Date(curr.date) >= comparedDate) acc.push(curr); return acc; }, []); console.log(response);

您可以使用sort ,然后获取数组中的第一个条目以获取具有最新日期的项目。

data.data.sort((a, b) => new Date(b.date) - new Date(a.date))[0];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM