배열의 최소 / 최대 날짜?
날짜 배열에서 최소 및 최대 날짜를 어떻게 찾을 수 있습니까? 현재 다음과 같은 배열을 만들고 있습니다.
var dates = [];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
이 작업을 수행하는 내장 함수가 있습니까? 아니면 직접 작성해야합니까?
코드는 IE, FF, Chrome으로 테스트되었으며 제대로 작동합니다.
var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));
다음과 같은 것 :
var min = dates.reduce(function (a, b) { return a < b ? a : b; });
var max = dates.reduce(function (a, b) { return a > b ? a : b; });
Chrome 15.0.854.0 dev에서 테스트 됨
_.min
및 _.max
날짜의 배열에서 작동; Lodash 또는 Underscore를 사용하는 경우이를 사용하고 아직 사용하지 않은 경우 Lodash (이러한 많은 유틸리티 기능을 제공하는) 사용을 고려하십시오.
예를 들면
_.min([
new Date('2015-05-08T00:07:19Z'),
new Date('2015-04-08T00:07:19Z'),
new Date('2015-06-08T00:07:19Z')
])
배열의 두 번째 날짜를 반환합니다 (가장 빠른 날짜이기 때문).
날짜는 UNIX epoch (숫자)로 변환되므로 Math.max / min을 사용하여 찾을 수 있습니다.
var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)
(Chrome에서만 테스트되었지만 대부분의 브라우저에서 작동합니다)
function sortDates(a, b)
{
return a.getTime() - b.getTime();
}
var dates = [];
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/28"))
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/27"))
var sorted = dates.sort(sortDates);
var minDate = sorted[0];
var maxDate = sorted[sorted.length-1];
데모 : http://jsfiddle.net/AlienWebguy/CdXTB/
** 분산 연산자 사용 | ES6 **
let datesVar = [ 2017-10-26T03:37:10.876Z,
2017-10-27T03:37:10.876Z,
2017-10-23T03:37:10.876Z,
2015-10-23T03:37:10.876Z ]
Math.min(...datesVar);
That will give the minimum date from the array.
Its shorthand Math.min.apply(null, ArrayOfdates);
ONELINER:
var min=dates.sort((a,b)=>a-b)[0], max=dates.slice(-1)[0];
result in variables min
and max
, complexity O(nlogn), editable example here. If your array has no-date values (like null
) first clean it by dates=dates.filter(d=> d instanceof Date);
.
var dates = [];
dates.push(new Date("2011-06-25")); // I change "/" to "-" in "2011/06/25"
dates.push(new Date("2011-06-26")); // because conosle log write dates
dates.push(new Date("2011-06-27")); // using "-".
dates.push(new Date("2011-06-28"));
var min=dates.sort((a,b)=>a-b)[0], max=dates.slice(-1)[0];
console.log({min,max});
var max_date = dates.sort(function(d1, d2){
return d2-d1;
})[0];
Same as apply, now with spread :
const maxDate = new Date(Math.max(...dates));
(could be a comment on best answer)
The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :
function getMax(dateArray, filler) {
filler= filler?filler:"";
if (!dateArray.length) {
return filler;
}
var max = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (max && d.valueOf()>max.valueOf()) {
max = d;
} else if (!max) {
max = d;
}
}
});
return max;
};
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));
function getMin(dateArray, filler) {
filler = filler ? filler : "";
if (!dateArray.length) {
return filler;
}
var min = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (min && d.valueOf() < min.valueOf()) {
min = d;
} else if (!min) {
min = d;
}
}
});
return min;
}
console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));
I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen
This is a particularly great way to do this (you can get max of an array of objects using one of the object properties): Math.max.apply(Math,array.map(function(o){return o.y;}))
This is the accepted answer for this page: Finding the max value of an attribute in an array of objects
Using Moment, Underscore and jQuery, to iterate an array of dates.
Sample JSON:
"workerList": [{
"shift_start_dttm": "13/06/2017 20:21",
"shift_end_dttm": "13/06/2017 23:59"
}, {
"shift_start_dttm": "03/04/2018 00:00",
"shift_end_dttm": "03/05/2018 00:00"
}]
Javascript:
function getMinStartDttm(workerList) {
if(!_.isEmpty(workerList)) {
var startDtArr = [];
$.each(d.workerList, function(index,value) {
startDtArr.push(moment(value.shift_start_dttm.trim(), 'DD/MM/YYYY HH:mm'));
});
var startDt = _.min(startDtArr);
return start.format('DD/MM/YYYY HH:mm');
} else {
return '';
}
}
Hope it helps.
참고URL : https://stackoverflow.com/questions/7143399/min-max-of-dates-in-an-array
'development' 카테고리의 다른 글
Flask는 URL 라우팅에서 정규식을 지원합니까? (0) | 2020.08.29 |
---|---|
SQLite 쿼리에서 정규식을 어떻게 사용합니까? (0) | 2020.08.29 |
setWidth (int pixels)는 dip 또는 px를 사용합니까? (0) | 2020.08.29 |
JSON에서 deserialize 및 serialize 란 무엇입니까? (0) | 2020.08.28 |
하드 부동 소수점 숫자와 소프트 부동 소수점 숫자의 차이점은 무엇입니까? (0) | 2020.08.28 |