简体   繁体   English

排序数组以首先从今天获得最近的

[英]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:您的代码可以改编为使用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);

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()结帐Array.sort()Date.getTime()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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