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:
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:
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.
Thanks in advance
You can use the array_filter() function to filter multidimensional array by date range using PHP. This example will show you how to filter array by specific date range in PHP. The following code snippet helps to filter last month events from an array using the array_filter() and strtotime() function in PHP.
The JavaScript filter array function is used to filter an array based on specified criteria. After filtering it returns an array with the values that pass the filter. The JavaScript filter function iterates over the existing values in an array and returns the values that pass.
The Array. filter() method is having an asynchronous behavior.
You need to return
the compairing value, either explicit
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()
);
I had an issue with this when the end date was the same as the start date to solve this issue I had to set the time on the end date to 23.59
const start = new Date().getTime()
const end=new Date()
end.setHours(23,59,59,999)
end.getTime()
return items.filter(item => {
let date = new Date(item.created_at).getTime();
return date >= start && date <= end;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With