1

I have dynamic date and time being generated and I need to sort them in descending order using JavaScript.

my data is in the below format.

var array= ["25-Jul-2017 12:46:39 pm","25-Jul-2017 12:52:23 pm","25-Jul-2017 12:47:18 pm"];

Anyone help would be appreciated.

4
  • array.sort((a,b) => new Date(b).getTime() - new Date(a).getTime()) Commented Jul 25, 2017 at 6:56
  • Possible duplicate of Sort Javascript Object Array By Date Commented Jul 25, 2017 at 6:57
  • @Rajesh - that's not cross browser friendly Commented Jul 25, 2017 at 6:57
  • Do you mean -? We can use ternary operator with a > b ? 1 : a < b : -1 : 0 Commented Jul 25, 2017 at 7:00

3 Answers 3

4

Here is the working code for you:

var array = ["25-Jul-2017 12:46:39 pm", "25-Jul-2017 12:52:23 pm", "25-Jul-2017 12:47:18 pm", "25-Jul-2017 12:59:18 pm"];

array.sort((a, b) => new Date(b).getTime() - new Date(a).getTime())

console.log(array)

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

5 Comments

that wont work in firefox - you're a chrome user, right?
Oh, didn't knew that. Yes, I did that in chrome.
Whoops. Yes @Rajesh. I think, while I was coding in the code-editor, you had already commented. Its a common sorting code.
@JaromandaX - Do you have know how we can make it work across browsers? what's the fix?
use a library like moment.js
0

var array = ["25-Jul-2017 12:46:39 pm", "25-Jul-2017 12:52:23 pm", "25-Jul-2017 12:47:18 pm"];

array.sort(function(a, b) {
  return new Date(b) - new Date(a);
});

console.log(array);

3 Comments

First its missing explanation. Second, please check other answer. Its already covered
Agree with @Rajesh. It's covered. Secondly, start using code editor so that people can see the output. And lastly, yes, you need to add some explanation about your answer.
Adding to @MilanChheda comment, <> icon is used to launch code editor. You can put your CSS/HTML/JS code and make it executable. This helps people to verify you code.
0

DEMO

var array= ["25-Jul-2017 12:46:39 pm","25-Jul-2017 12:52:23 pm","25-Jul-2017 12:47:18 pm"];
var dateAr = [];

for(var i=0;i<array.length;i++){
 dateAr.push(new Date(array[i].replace(/-/g,'/')).getTime()); //convert to milisecond
}


var sortAr = dateAr.sort(function (a, b) {  return a - b;  }); //sort it

var resArr = [];
for(var i=0;i<array.length;i++){
 resArr.push(new Date(sortAr[i])); //make date object
}
console.log(resArr);

Convert to millisecond from Date , and then sort it. and make Date object from millisecond. use this replace(/-/g,'/') to replace date string, it works in all browser.

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.