0

Let's say I have an object of this type and I want to sort the figsList array in that object based on createdAt property (latest first). How can I achieve this in JavaScript?

I want to perform this operation in my NodeJS backend.

{
  id,
  name,
  figsList[
    {
      ...
      createdAt: DateTime
      ...
    },
    {
      ...
      createdAt: DateTime
      ...
    },
    {
      ...
      createdAt: DateTime
      ...
    },
  ]
}

1 Answer 1

3

You can simply use .sort() method. .sort() takes a callback function, which takes as parameters 2 objects contained in the array. In your case you can try with:

figsList.sort((a, b) => (a.createdAt > b.createdAt) ? 1 : -1)

When we return a positive value, the function communicates to sort() that the object b takes precedence in sorting over the object a. Returning a negative value will do the opposite.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. This worked but with a little change. .sort((a, b) => (b.createdAt > a.createdAt) ? 1 : -1) as I wanted the latest created one at top.
Yes, my answer will sort the array ascending.
yes, even changing 1 : -1 to -1 : 1 sorted it to descending. It worked.

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.