Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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"
  }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!