我已经搜索过这个问题,但似乎没有适用的现有答案。请考虑以下事项:
[
{ 'August 17th 2016': [75] }, // 75 is the length of the array which contains up to 75 objects ...
{ 'August 1st 2016': [5] },
{ 'August 28th 2016': [5] },
...
]
按日期对该数组中的对象进行排序并仍然保留其键的“英文”表示的最佳方法是什么?
注意:键用作图表标签。
我看到的所有地方都使用了 array.sort
,但那是在 created_at
对象的键上。
结果应该是:
[
{ 'August 1st 2016': [5] },
{ 'August 17th 2016': [75] }
{ 'August 28th 2016': [5] },
...
]
我不确定如何继续,所以我没有任何东西可以显示。
最佳答案
这可以通过在对象键上使用 date.parse
来完成。我使用了第一个对象键,因为它在数组的每个条目中似乎只有 1 个。棘手的部分是 date.parse
对“12th”或“1st”不起作用,因此,我们必须暂时用 ,
。这样,date.parse
就可以处理字符串。
var dates = [{
'August 17th 2016': [75]
}, {
'August 1st 2016': [5]
}, {
'August 28th 2016': [5]
}]
const replaceOrdinals = o => {
return Object.keys(o)[0].replace(/\w{2}( \d+$)/, ',$1');
}
dates = dates.sort((a, b) => {
return Date.parse(replaceOrdinals(a)) - Date.parse(replaceOrdinals(b))
});
console.log(dates);
请记住:
评论来自@adeneo:Date.parse
是实现依赖的。您可能想要通读它的文档以确定时区之类的东西是否会把事情搞砸。作为更可靠的方法,您可以使用类似 moment.js 的方法进行日期解析。
关于javascript - 如何对键为日期的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090057/