Home > front end >  Sort array to get the nearest from today first
Sort array to get the nearest from today first

Time:10-27

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

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

  • Related