1

I have an array with this format. I just want to pull the 1 oldest date.

This is value in array looks like:

Array:

creationDate = ['Wed Feb 13 21:14:55 GMT 2019','Wed Feb 13 21:19:42 GMT 2019','Wed Feb 13 21:28:29 GMT 2019','Wed Feb 13 21:31:04 GMT 2019'];

This is my code:

Code:

        // this below code is not working as expected   
        if(creationDate){
            var orderedDates = creationDate.sort(function(a,b){
                return Date.parse(a) > Date.parse(b);
            }); 
        }

Expected Result:

Wed Feb 13 21:14:55 GMT 2019

1
  • 1
    Try using Date.parse(a) - Date.parse(b) (or switch a and b to sort in the opposite order). The compare function expects a number to be returned rather than a boolean. Check rules for thee compare function here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Mar 20, 2019 at 23:36

3 Answers 3

6

You can use Array.reduce() and on each iteration compare the dates and take the oldest:

const creationDate = ['Wed Feb 13 21:14:55 GMT 2019','Wed Feb 13 21:19:42 GMT 2019','Wed Feb 13 21:28:29 GMT 2019','Wed Feb 13 21:31:04 GMT 2019'];

const oldest = creationDate.reduce((c, n) => 
  Date.parse(n) < Date.parse(c) ? n : c
);

console.log(oldest);

Sign up to request clarification or add additional context in comments.

1 Comment

Better than sorting as it doesn't mutate the original array like sort does.
5

You want to return a number, not a Boolean (so use - not >):

var creationDate = ['Wed Feb 13 21:14:55 GMT 2019', 'Wed Feb 13 21:19:42 GMT 2019', 'Wed Feb 13 21:28:29 GMT 2019', 'Wed Feb 13 21:31:04 GMT 2019', 'Wed Feb 13 21:33:04 GMT 2019'];
var orderedDates = creationDate.sort(function(a, b) {
  return Date.parse(a) - Date.parse(b);
});
console.log(orderedDates[0]);

Comments

1

Try:

if(creationDates){
  return creationDates.sort()[0]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.