简体   繁体   中英

Sort array to get the nearest from today first

I have an array like this :

array = [
  {
    "title": "a",
    "date": "2021-10-25T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-20T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-28T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-30T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-26T18:00:00.000"
  }
]

And I want to sort it with the nearest object from today first. I try with sort but I think, I don't have the good method to do this.

This is what I tried :

array.sort((a, b) => {
   return (new Date(b.battle_start) > new Date()) - (new Date(a.battle_start) < new Date())
})

And this is what I want

array = [
  {
    "title": "b",
    "date": "2021-10-26T18:00:00.000"
  },
  {
    "title": "a",
    "date": "2021-10-25T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-28T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-30T18:00:00.000"
  },
  {
    "title": "b",
    "date": "2021-10-20T18:00:00.000"
  }
]

Your code can be adapted to use Math.abs , so that distance to past or future will be regarded in the same way:

 const array = [{"title": "a","date": "2021-10-25T18:00:00.000"},{"title": "b","date": "2021-10-20T18:00:00.000"},{"title": "b","date": "2021-10-28T18:00:00.000"},{"title": "b","date": "2021-10-30T18:00:00.000"},{"title": "b","date": "2021-10-26T18:00:00.000"}]; let now = Date.now(); array.sort((a,b) => Math.abs(Date.parse(a.date) - now) - Math.abs(Date.parse(b.date) - now) ); console.log(array);

You should be able to do that via :

array.sort((a, b) => {
  return (Math.abs(new Date(a.battle_start) - new Date())) - Math.abs((new Date(b.battle_start) - new Date()))
})

What you want to compare is the distance between "now" and the target date.

 array = [ { "title": "a", "date": "2021-10-25T18:00:00.000" }, { "title": "b", "date": "2021-10-20T18:00:00.000" }, { "title": "b", "date": "2021-10-28T18:00:00.000" }, { "title": "b", "date": "2021-10-30T18:00:00.000" }, { "title": "b", "date": "2021-10-26T18:00:00.000" } ] array.sort((a,b) => new Date(b.date).getTime() - new Date(a.date).getTime()) console.log(array);

The above snippet will sort your array from the nearest date. Checkout Array.sort() and Date.getTime()

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