javascript 如何使用javascript在数组中找到最早的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20079837/
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
how to find earliest date in an array using javascript
提问by user3010195
how to find earliest date i.e min date in an array using javascript? Example:I have an array a holding
如何使用javascript在数组中找到最早的日期,即最小日期?示例:我有一个数组
{10-Jan-2013,12-Dec-2013,1-Sep-2013,15-Sep-2013}
My output should be :
我的输出应该是:
{10-Jan-2013,1-Sep-2013,15-Sep-2013,12-Dec-2013}.
How can i do this?
我怎样才能做到这一点?
回答by David says reinstate Monica
I'd suggest passing an anonymous function to the sort()
method:
我建议将匿名函数传递给该sort()
方法:
var dates = ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013'],
orderedDates = dates.sort(function(a,b){
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates); // ["10-Jan-2013", "1-Sep-2013", "15-Sep-2013", "12-Dec-2013"]
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
orderedDates = dates.sort(function(a, b) {
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates);
Note the use of an array ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013']
of quoted date-strings.
请注意使用带['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013']
引号的日期字符串数组。
The above will give you an array of dates, listed from earliest to latest; if you want only the earliest, then use orderedDates[0]
.
以上将为您提供一系列日期,从最早到最晚列出;如果你只想要最早的,那么使用orderedDates[0]
.
A revised approach, to show only the earliest date – as requested in the question – is the following:
修改后的方法,只显示最早的日期——如问题所要求的——如下:
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
earliest = dates.reduce(function (pre, cur) {
return Date.parse(pre) > Date.parse(cur) ? cur : pre;
});
console.log(earliest); // 10-Jan-2013
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
earliest = dates.reduce(function(pre, cur) {
return Date.parse(pre) > Date.parse(cur) ? cur : pre;
});
console.log(earliest);
References:
参考:
回答by driangle
Assuming you have an array of Date
objects.
假设你有一个Date
对象数组。
function findEarliestDate(dates){
if(dates.length == 0) return null;
var earliestDate = dates[0];
for(var i = 1; i < dates.length ; i++){
var currentDate = dates[i];
if(currentDate < earliestDate){
earliestDate = currentDate;
}
}
return earliestDate;
}