Ah, yes. Unfortunately, Node ensures that object keys which appear to be numeric are stored/retrieved in ascending order, which I’d forgotten. The solution becomes a little more complex:
getyears(category) {
const result = Events.find({ category })
.fetch()
.map(doc => doc.thedate.substr(0, 4))
.reduce((years, year) => {
if (year in years) {
years[year]++;
} else {
years[year] = 1;
}
return years;
}, {});
return Object.keys(result).sort((a, b) => ~~b - ~~a)
.map(year => ({ year, count: result[year] }));
}
The result is now an array of objects, such as:
[
{
"year": "2019",
"count": 1
},
{
"year": "2018",
"count": 5
},
{
"year": "2011",
"count": 3
}
]
Which means you will need to alter your presentation code accordingly.
Alternatively, you could use the original code, but ensure the year is prefixed with a space, which is sufficient to ensure that the order is preserved. The map would then look like:
.map(doc => ` ${doc.thedate.substr(0, 4)}`)
and you can continue to use your current presentation code.