3

I'm trying to sort the date from this array of objects from the latest to the oldest. I'm trying this code, i.e. copy the array to a new const and then use it with sort, but I have the same result, no sorted date. My code is below:

const array=[...user?.editedBy]
console.log(array,"array")

const sortedDates = array?.sort((dateA, dateB) => dateB.date -dateA.date )
console.log(sortedDates,'sortedArray')

The first pic is the console log from the array and the second from sortedDates.

So the same result, can someone please help me figure out what I'm missing?

Thank you in advance

enter image description here enter image description here

1
  • 3
    Those are strings not dates, wrap them with new Date() before comparison. Commented Jan 25, 2022 at 21:06

1 Answer 1

4

As you can see in your console screenshot, those aren't actually Date objects, but strings.

So you have to map the strings to Date objects and compare them afterward.

const sortedDates = array?
  .map(obj => { return { ...obj, date: new Date(obj.date) } })
  .sort((a, b) => b.date - a.date)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the answer it does work, but I need in this array the other data as like id and the rest, this array now its returning just date. How do I fix that
Oh, didn't see that. I fixed my answer. Works now?
You're welcome, please accept the answer to improve the visibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.