我想使用日期进行过滤,但数据采用JSON格式。如何在JavaScript中使用日期过滤大型数据集?
示例:
data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]
答案 0 :(得分:5)
如果您只是想按时间过滤数据,可以像这样查看数组中的所有对象:
var filteredData = [];
for(var index in data) {
var obj = data[index];
var date = parseDate(obj.date);
//Filter dates from 2011 and newer
if(date > new Date(2011, 0, 1))
filteredData.push(obj);
}
function parseDate(dateStr) {
var date = dateStr.split('-');
var day = date[0];
var month = date[1] - 1; //January = 0
var year = date[2];
return new Date(year, month, day);
}
//Filtered data now contains:
// [{"date":"22-12-2014","name":"selva"},{"date":"11-11- 2011","name":"suresh"}]
我确信您可以更好地完成解析日期,例如以Date构造函数接受的格式定义日期。
答案 1 :(得分:5)
要获取与特定日期匹配的元素集,您可以使用filter
将它们提取到新数组中。
function getByDate(date){
return data.filter(function (el) {
return el.date == date;
});
}
var arr = getByDate('11-11-2011');
要按日期对数据集进行排序,首先需要将日期字符串转换为JS日期对象。这涉及稍微调整日期字符串,以便可以正确解析。
function reformatDate(date) {
return arr = date.split('-').reverse();
}
var sortByDate = function (a, b) {
return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};
data.sort(sortByDate);
答案 2 :(得分:1)
要获取与特定日期匹配的元素集,您可以使用过滤器将它们提取到新数组中。
var tempArray= data.filter(function (d, i) {
return d >= startDate && d <= endDate;
})
答案 3 :(得分:1)
我使用日期格式MM / DD / YY。这是完整的例子 -
var data=[
{date:'02/10/2018',name:'date is 10'},
{date:'02/14/2018',name:'date is 14'},
{date:'02/16/2018',name:'date is 16'},
{date:'02/20/2018',name:'date is 20'},
{date:'02/24/2018',name:'date is 24'},
{date:'02/26/2018',name:'date is 26'},
{date:'02/30/2018',name:'date is 30'},
{date:'03/01/2018',name:'date is 01'},
{date:'03/05/2018',name:'date is 05'},
{date:'02/23/2018',name:'date is name 23'},
]
var today = new Date();
var todayTime = new Date().getTime();
var days_after_20 = new Date().setDate(today.getDate()+20);
var days_before_5 = new Date().setDate(today.getDate()-5);
var result = data.filter(function (item) {
var itemTime = new Date(item.date).getTime()
return itemTime >= days_before_5 && itemTime <= days_after_20;
})
console.log(result);