-1

I have an array with objects and each contain date in the format : day ' month ' year

Here is the example of single object in that array

{
    "title": "“All’Improvviso” - Cajo Fabricio",
    "artist": "Johann Adolf Hasse",
    "link": "https://www.facebook.com/AllimprovvisoFestivalGliwice",
    "day": "sobota, godz. 18:00",
    **"date": "26 ' 06 ' 2021",**
    "place": "Ruiny Teatru Victoria",
    "city": "Gliwice",
    "canceled": false,
    "ticketSoon": false
}

I want to create a new array from this objects with the descending order of a date.

Can anyone help? I am making the calculations in Nuxt project

lemonadia
  • 19
  • 2
  • Please add your array in post and along with the code you have tried. – Hassan Imam Dec 16 '21 at 14:13
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+sort+object+array+date+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Dec 16 '21 at 14:16
  • `const [dd,mm,yyyy] = "26 ' 06 ' 2021".split(" ' "); const date = new Date(yyyy,mm-1,dd,15,0,0,0); // create a normalised date` – mplungjan Dec 16 '21 at 14:19

1 Answers1

0

Parse the string as date and then sort the array in order of date

const data = [{
  "artist": "Johann Adolf Hasse",
  "date": "26 ' 06 ' 2021",
}, {
  "artist": "Test Hasse",
  "date": "23 ' 06 ' 2021",

}];

const sortedData = data.map(item => {
  const splitDate = item.date.split("'");
  const newDate = new Date(splitDate[2].trim(), splitDate[1].trim(), splitDate[0].trim());
  return { ...item,
    date: newDate
  }
}).sort((a, b) => {
  return new Date(a.date) - new Date(b.date)

})
console.log(sortedData)
brk
  • 48,835
  • 10
  • 56
  • 78