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

140
Views
How can I show the latest data by date using sort in react typescript

My date format is like this: Mon Mar 07 2022 and I want to show the latest data. I have tried this way but it's not working.

If I put new Date() into my code I got this error: var Date: DateConstructor new (value: string | number | Date) => Date (+3 overloads) The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

 useEffect(() => {
        setIsLoading(true)
        fetch(`http://localhost:5000/dashboard/orders`)
            .then(res => res.json())
            .then(data => {
                const latestData = data.sort((a, b) => b.date - a.date)
// const latestData = data.sort((a, b) => new Date(b.date) -new Date( a.date)) // error
                setOrders(latestData)
            })
            .finally(() => setIsLoading(false))
    }, [])
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Please Try this way

data.sort(function(a,b){
  return new Date(b.date) - new Date(a.date);
});
about 4 years ago · Juan Pablo Isaza Report

0

This is a typescript error, the sort comparator function accepts only numbers.

Note: Without getTime it works in javascript.

const data = [{
    date: "Mon Mar 07 2022",
  },
  {
    date: "Mon Mar 01 2022",
  },
  {
    date: "Mon Mar 06 2022",
  },
];
const latestData = data.sort(
  (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
);
console.log(latestData);

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!