Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

revere array object based on year and month

i have bellow array object

var dataset = [
               {
                "data" : "Country",
                "title" : "country"
               },
               {
                "data" : "Jan 2023",
                "title" : "Jan 2023"
               },
               {
                "data" : "Feb 2023",
                "title" : "Feb 2023"
               },
               {
                "data" : "Dec 2022",
                "title" : "Dec 2022"
               },
               ]

what i want is to keep the first index as it is by year 2022 then followed by 2023 in month order like below

var dataset = [
               {
                "data" : "Country",
                "title" : "country"
               },
               {
                "data" : "Dec 2022",
                "title" : "Dec 2022"
               },
               {
                "data" : "Jan 2023",
                "title" : "Jan 2023"
               },
               {
                "data" : "Feb 2023",
                "title" : "Feb 2023"
               },

               ]

so for example if 2022 Nov is then Nov should come fist then Dec 2022. the original array already sorted with latest year first then followed by last year. so means original array always has latest year month first.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i try array sort but was not able archive

 var newdataset  = dataset.sort((a, b) => {
      if (a !== columns[0] && b !== columns[0]) { 
      return b.data.length - a.data.length
      }
  })

>Solution :

Compare the date values constructed from each dataset data.

let dataset = [{
    "data": "Country",
    "title": "country"
  },
  {
    "data": "Feb 2023",
    "title": "Feb 2023"
  },
  {
    "data": "Dec 2022",
    "title": "Dec 2022"
  },
  {
    "data": "Jan 2023",
    "title": "Jan 2023"
  },
  {
    "data": "Nov 2022",
    "title": "Nov 2022"
  },
]

const [heading, ...rest] = dataset;

dataset = [heading, ...rest.sort((a, b) => {
  return new Date(a.data) - new Date(b.data);
})];

console.log(dataset);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading