1

I have array of object contain date format. code works only for ordering the day not for months and years

My Code

const bills = [
  {
    name: "ghaith",
    type: "transport",
    date: "12 may 21",
  }, 
  {
    name: "Alex",
    type: "Restaurants",
    date: "15 oct 20",
  }
];

bills.sort((a, b) => b.date < a.date ? 1 : -1)

4
  • 1
    That isn't valid JavaScript. Please correct so that readers can see exactly what you're working with. Also, there's rarely a good reason to ever store dates in a suboptimal, language and geo-specific format such as "12 mai 21". Always use ISO8601. Commented Oct 26, 2021 at 13:01
  • This is invalid date format. Commented Oct 26, 2021 at 13:04
  • bills.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()) ... which of cause works for valid date shorthand formats only ... the OP e.g. did provide originally "12 mai 21" whereas it should be "12 may 21" ... it's fixed/edited already. Commented Oct 26, 2021 at 13:12
  • @GhaithDiab ... regarding the provided solutions, are there any questions left? Commented Oct 29, 2021 at 7:52

2 Answers 2

2

From the above comment ...

"bills.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()) ... which of cause works for valid date shorthand formats only ... the OP e.g. did provide originally "12 mai 21" whereas it should be "12 may 21" ... it's fixed/edited already."

const bills = [{
  name: "ghaith",
  type: "transport",
  date: "12 may 21",
}, {
  name: "Alex",
  type: "Restaurants",
  date: "15 oct 20",
}];

console.log(
  bills.sort((a, b) =>
    // new Date(a.date).getTime() - new Date(b.date).getTime()
    // or directly without `getTime` ...
    new Date(a.date) - new Date(b.date)
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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

Comments

1

You can use this below code to sort your array of object by date has specific format:

    const bills = [{
      name: "ghaith",
      type: "transport",
      date: "12 may 21",
    }, {
      name: "Alex",
      type: "Restaurants",
      date: "15 oct 20",
    }];


    console.log(
      bills.sort((a, b) => new Date(a.date) - new Date(b.date))
    );

2 Comments

Welcome to SO. And thanks for the working solution (hence the upvote). And also allow me a note ... There is no need to additionally assign the return value of sort to an extra variable. Since sort does mutate the array it is operating, sortedBills is equal to the (just sorted) bills ... sortedBills === bills is true.
@PeterSeliger thanks for your upvote and I have updated my answer as per your note. I think now its ok.

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.