typescript 按两个日期之间的日期过滤数组中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48227286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter Array in Array by date between 2 dates
提问by Max R.
I am trying to filter a data-array of a LineChart by the from-date / to-date input of a user in TypeScript for my Angular App. The data array has the following structure:
我正在尝试通过用户在 TypeScript 中为我的 Angular 应用程序输入的起始日期/截止日期来过滤 LineChart 的数据数组。数据数组具有以下结构:
var multi = [
{
"name": "test1",
"series": [
{
"date": new Date("2018-01-01T01:10:00Z"),
"value": 44
},...
]
},
{
"name": "test2",
"series": [
{
"date": new Date("2018-01-01T01:10:00Z"),
"value": 38
},...
]
},
{
"name": "test3",
"series": [
{
"date": new Date("2018-01-01T01:10:00Z"),
"value": 33
},...
]
}
];
I now want to filter the items of the array by the criteria that the date inside is after a 'fromDate' and before a 'toDate'. I tried the following:
我现在想根据里面的日期在“fromDate”之后和“toDate”之前的条件来过滤数组的项目。我尝试了以下方法:
obj.forEach(data => {
console.log(data.name);
data.series = data.series.filter((item: any) => {
item.date.getTime() >= fromDate.getTime() &&
item.date.getTime() <= toDate.getTime();
});
});
the obj[]
array has an empty obj[i].series
array afterwards. Can anybody help me here? The iteration seems to be right since debugging gave me all the dates, also the true/False statements from the date comparing was right as well.
该obj[]
阵列具有一个空的obj[i].series
阵列之后。有人可以帮我吗?迭代似乎是正确的,因为调试给了我所有的日期,日期比较中的真/假语句也是正确的。
Thanks in advance
提前致谢
回答by Nina Scholz
You need to return
the compairing value, either explicit
您需要return
比较值,要么是明确的
data.series = data.series.filter((item: any) => {
return item.date.getTime() >= fromDate.getTime() &&
item.date.getTime() <= toDate.getTime();
});
or without the brackets, implicit.
或不带括号,隐式。
data.series = data.series.filter((item: any) =>
item.date.getTime() >= fromDate.getTime() && item.date.getTime() <= toDate.getTime()
);
回答by Dazzle
let start = new Date(this.min);
let end = new Date(this.max);
return items.filter(item => {
let date = new Date(item.created_at);
return date >= start && date <= end;
}