The*_*ebs 6 javascript arrays sorting date-parsing
我搜索过这个问题,似乎没有现成的答案.考虑以下:
[
{ '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] },
...
]
Run Code Online (Sandbox Code Playgroud)
按日期排序此数组中对象的最佳方法是什么,并保持其键的"英语"表示?
注意:该键用作图表标签.
我看到的每个地方都array.sort
被使用,但那是对象的关键所在created_at
.
结果应该是:
[
{ 'August 1st 2016': [5] },
{ 'August 17th 2016': [75] }
{ 'August 28th 2016': [5] },
...
]
Run Code Online (Sandbox Code Playgroud)
我不知道该怎么办,所以我没有什么可展示的.
这可以通过date.parse
在对象键上使用来完成.我拿了第一个对象键,因为它看起来在数组的每个条目中只有1个.棘手的部分是date.parse
在"12th"或"1st"上不起作用,因此,我们必须暂时用"th"替换"th"或"st" ,
.这样,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);
Run Code Online (Sandbox Code Playgroud)
记住:
来自@adeneo的评论:Date.parse
依赖于实现.您可能希望阅读它的文档,以确定时区之类的东西是否会搞砸.作为一种更确定的方法,您可以使用类似moment.js的东西进行日期解析.
归档时间: |
|
查看次数: |
125 次 |
最近记录: |