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

115
Views
CreatedAt in MongoDB can´t be sorted

This is a Sort example : const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a});

Array products

 let a = [{
    "_id": "61ce7052b2c78ab4ae89c731",
    "title": "Alcohol",
    "description": "Para medicina",
    "categories": [
        "Art"
    ],
    "price": 300,
    "rating": 1,
    "image": "https://veterinariaeljockey.com.ar/wp-content/uploads/2020/12/alcohol-etilico-purocol-500cc.jpg",
    "quantity": 3,
    "createdAt": "2021-12-31T02:52:02.833Z",
    "updatedAt": "2021-12-31T02:52:02.833Z",
    "__v": 0
},
 {
    "_id": "61ce6fefb2c78ab4ae89c72e",
    "title": "Liquido de Frenos",
    "description": "Elemento para el auto",
    "categories": [
        "Services"
    ],
    "price": 2500,
    "rating": 1,
    "image": "http://proyesa.com.sv/site/wp-content/uploads/2017/02/liquido-para-frenos-bosch.jpg",
    "quantity": 23,
    "createdAt": "2021-12-31T02:50:23.974Z",
    "updatedAt": "2021-12-31T02:50:23.974Z",
    "__v": 0
}
]

Sort

    useEffect(() => {
    if (time === "newest") {
      if (!filterProducts || filterProducts.length == 0) {
        setFilterProducts(...products);
      } else {
        setFilterProducts((prev) =>
          [...prev].sort((a, b) => a.createdAt - b.createdAt)
        );
      }
    } else {
      setFilterProducts((prev) => [...prev].sort((a, b) => b.createdAt - a.createdAt));
    }
  }, [time]);

When I touch "Newest" products sort by default. But I touch "Oldest" nothing happens

Thanks for helping!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

createdAt is a string, in order to sort the list by date you must convert it into Date.

example:

 setFilterProducts((prev) =>
    [...prev].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
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!