简体   繁体   中英

JavaScript, sort object by latest date and time values

Beginner here.
I want to sort the whole object array, by date and time values. Latest date and time first.

My problem.
Not sure how to sort with different key values, by date and time.
Example: I have key values start , stop and turn . I want to sort this by date and time. I would still like to keep the key values as a reference to that value.

{
  "start 0": "2017-10-24T03:15:36Z",
  "start 1": "2017-10-24T09:13:44Z",
  "start 2": "2017-10-24T15:41:27Z",
  "stop 0": "2017-10-23T21:40:27Z",
  "stop 1": "2017-10-24T03:47:20Z",
  "stop 2": "2017-10-24T09:42:34Z",
  "turn 0": "2017-10-22T16:02:51Z",
  "turn 1": "2017-10-23T22:13:56Z",
  "turn 2": "2017-10-23T03:19:20Z"
}

I am using moment.js

Thanks in advance

{
  "start 0": "2017-10-24T03:15:36Z",
  "start 1": "2017-10-24T09:13:44Z",
  "start 2": "2017-10-24T15:41:27Z",
  "stop 0": "2017-10-23T21:40:27Z",
  "stop 1": "2017-10-24T03:47:20Z",
  "stop 2": "2017-10-24T09:42:34Z",
  "turn 0": "2017-10-22T16:02:51Z",
  "turn 1": "2017-10-23T22:13:56Z",
  "turn 2": "2017-10-23T03:19:20Z"
}

is an object and since javascript objects have no order, sorting doesn't make sense

What you have is an object, but if we assume you have the following array: var datesArr =["2017-10-24T03:15:36Z","2017-10-24T03:15:36Z","2017-10-24T15:41:27Z"];

What you need in order to sort those is: datesArr.sort((a,b)=> new Date(b) - new Date(a))

try this

res =
{ 'start 0': '2017-10-24T03:15:36Z',
  'start 1': '2017-10-24T09:13:44Z',
  'start 2': '2017-10-24T15:41:27Z',
  'stop 0': '2017-10-23T21:40:27Z',
  'stop 1': '2017-10-24T03:47:20Z',
  'stop 2': '2017-10-24T09:42:34Z',
  'turn 0': '2017-10-22T16:02:51Z',
  'turn 1': '2017-10-23T22:13:56Z',
  'turn 2': '2017-09-23T03:19:20Z' }

// console.log(res);
myarr = []
Object.keys(res).forEach( key => {
   console.log(key+" = "+res[key]);
   myarr.push({ 'key': key, 'stamp': res[key]});
}
);
// console.log(myarr);
myarr.sort(function(a, b) { 
    return new Date(a.stamp) - new Date(b.stamp) > 0;
})

// console.log(sorted);
for(var i in myarr){

  console.log(myarr[i]);

}

repl link

var array=[{
  "date": "2017-10-24T03:15:36Z"},
           {"date": "2017-10-24T09:13:44Z"},
           {"date": "2017-10-24T15:41:27Z"},
           {"date": "2017-10-23T21:40:27Z"},{
  "date": "2017-10-23T03:19:20Z"}
]

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

try something like this , keys should be same in every object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM