Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the earliest date in an array using JavaScript

Tags:

javascript

How can I find the earliest date, i.e. minimum date, in an array using JavaScript?

Example:

["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?

like image 394
user3010195 Avatar asked Nov 19 '13 19:11

user3010195


People also ask

What is the first index of an array in JavaScript?

Note. In an array, the first element has index (position) 0, the second has index 1, ...

Is date in array JavaScript?

To check if a date is contained in an array:Use the find() method to iterate over the array. On each iteration, check if the date's timestamp is equal to a specific value. If the date is not found, the find method returns undefined .

How do you declare a date variable in JavaScript?

var date1 = new Date(); date1. setFullYear(2011, 6, 1); // 2011-07-01, ok console. log(date1); // set date2 the same date as date1 var date2 = date1; // ... // now I'm gonna set a new date for date2 date2. setFullYear(2011, 9, 8); // 2011-10-08, ok console.


1 Answers

I'd suggest passing an anonymous function to the sort() method:

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);

JS Fiddle demo.

Note the use of an array ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013'] of quoted date-strings.

The above will give you an array of dates, listed from earliest to latest; if you want only the earliest, then use 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);

JS Fiddle demo.

References:

  • Date.parse().
  • Array.prototype.reduce().
  • Array.prototype.sort().
like image 135
David Thomas Avatar answered Oct 06 '22 01:10

David Thomas