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.
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);