0

I have a data which consists of accessTime as a key which is actually a date in strong format i want to sort that accesstime in desending order.

[
0: {
accessTime: "2019-12-05 03:11:11"
id: "CBA567E1-8B8B-A88A-7A21-AD30C140502D"
name: "test proc"
type: "0"
version: "1"
},
{
accessTime: "2019-12-05 03:12:35"
id: "87DB7B7A-37C8-9BD7-D12C-D5548E402B13"
name: "testProcess88"
type: "0"
version: "1"
},
{
accessTime: "2019-12-05 03:12:48"
id: "73005C00-9FEF-762D-0FC5-D554C27B7A22"
name: "testprocess89"
type: "0"
version: "1"
}
]

Data is array of an object i have to sort this data on the basis of accessTime field in desending order please can some one suggest some function or so.

I have tried with this code but it is not working for me :

  sort(arr, key) {
    return arr.sort((a, b) => (a[key].toLowerCase() > b[key].toLowerCase()) ? 1 : ((b[key].toLowerCase() > a[key].toLowerCase()) ? 0 : -1));
  }

please help

Mayank Purohit
  • 163
  • 1
  • 4
  • 17
  • 1
    If that date is returned from some kind of API, I would recommend you to ask to return it in ISO string format instead, otherwise you have to assume the timezone, which is misleading. I would address this issue before actually sorting and parsing. – briosheje Dec 05 '19 at 11:25
  • backend is something we cannot change now – Mayank Purohit Dec 05 '19 at 11:36

2 Answers2

0

Your approach is almost correct, but you need to parse the dates to be able to compare them like that:

sort = function(arr, key) {
    return arr.sort((a, b) => (new Date(b[key]) - new Date(a[key])));
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Example:

sort = function(arr, key) {
    return arr.sort((a, b) => (new Date(b[key]) - new Date(a[key])));
}
var arr = [
{
accessTime: "2019-12-05 03:11:11",
id: "CBA567E1-8B8B-A88A-7A21-AD30C140502D",
name: "test proc",
type: "0",
version: "1"
},
{
accessTime: "2019-12-05 03:12:35",
id: "87DB7B7A-37C8-9BD7-D12C-D5548E402B13",
name: "testProcess88",
type: "0",
version: "1"
},
{
accessTime: "2019-12-05 03:12:48",
id: "73005C00-9FEF-762D-0FC5-D554C27B7A22",
name: "testprocess89",
type: "0",
version: "1"
}
]
console.log(sort(arr, "accessTime"))

https://jsbin.com/ditijeseva/1/edit?js,console

Glenn van Acker
  • 317
  • 1
  • 14
0

Try this

arr.sort((a,b)=>{
let c=new Date(a.accessTime);
  let d=new Date(b.accessTime);
  if(c>d) return -1;
  if(c<d) return 1;
  return 0;
});
Gogul
  • 298
  • 2
  • 14