簡體   English   中英

排序數組以首先從今天獲得最近的

[英]Sort array to get the nearest from today first

我有一個這樣的數組:

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) => {
   return (new Date(b.battle_start) > new Date()) - (new Date(a.battle_start) < new Date())
})

這就是我想要的

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"
  }
]

您的代碼可以改編為使用Math.abs ,以便以相同的方式看待過去或未來的距離:

 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);

您應該能夠通過以下方式做到這一點:

array.sort((a, b) => {
  return (Math.abs(new Date(a.battle_start) - new Date())) - Math.abs((new Date(b.battle_start) - new 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);

上面的代碼段將從最近的日期對您的數組進行排序。 結帳Array.sort()Date.getTime()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM