最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter JSON by range dates JS - Stack Overflow

programmeradmin2浏览0评论

I want to filter a simple JSON file by date range. With a start date and and end date.

And this is my function:

var startDate = new Date("2013-3-25");
var endDate = new Date("2017-3-25");
var aDate = new Date();

var filteredData = this.orders.filter(function(a){
aDate = new Date(a.fecha);
    aDate >= startDate && aDate <= endDate;
});
console.log(filteredData)

Here's my: fiddle

I'm expecting to get one object in my array, however the array is empty as you can see in the console.

I want to filter a simple JSON file by date range. With a start date and and end date.

And this is my function:

var startDate = new Date("2013-3-25");
var endDate = new Date("2017-3-25");
var aDate = new Date();

var filteredData = this.orders.filter(function(a){
aDate = new Date(a.fecha);
    aDate >= startDate && aDate <= endDate;
});
console.log(filteredData)

Here's my: fiddle

I'm expecting to get one object in my array, however the array is empty as you can see in the console.

Share Improve this question edited Nov 26, 2020 at 7:50 1x2x3x4x asked Jan 10, 2018 at 14:29 1x2x3x4x1x2x3x4x 6049 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

When you use the filter method on an array, that function needs to return a boolean to indicate to the script whether to keep a value or remove it.

You didn't return the value from within the filter function. This works:

var filteredData = this.orders.filter(function(a){
    aDate = new Date(a.fecha);
    return aDate >= startDate && aDate <= endDate;
});

however the array is empty as you can ses in the console.

Because filter's callback method is not returning anything, make it

var filteredData = this.orders.filter(function(a){
    var aDate = new Date(a.fecha);
    return aDate.getTime() >= startDate.getTime() && aDate.getTime() <= endDate.getTime();
});

Note

  • Date parison is done differently, check this answer.
  • You need not do getTime() on startDate and endDate for every iteration, do it once before the filter

You aren't returning anything in your filter.

var filteredData = this.orders.filter(function(a){
    aDate = new Date(a.fecha);
    return aDate >= startDate && aDate <= endDate;
});

For reference, https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

发布评论

评论列表(0)

  1. 暂无评论