如何对键为日期的对象数组进行排序

How to sort array of objects where keys are dates

我已经搜索过这个问题,但似乎没有适用的现有答案。考虑以下因素:

[
  { '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] },
  ...
]

按日期对该数组中的对象排序并仍然保留其键的 "english" 表示的最佳方法是什么?

注意:该键用作图表标签。

我看到的所有地方都使用了 array.sort,但那是在对象的键 created_at.

结果应该是:

[
  { 'August 1st 2016': [5] },
  { 'August 17th 2016': [75] }
  { 'August 28th 2016': [5] },
  ...
]

我不确定如何继续,所以我没有任何东西可以显示

这可以通过在对象键上使用 date.parse 来完成。我使用了第一个对象键,因为它在数组的每个条目中似乎只有 1 个。棘手的部分是 date.parse 对“12th”或“1st”不起作用,因此,我们必须暂时用 , 替换 "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+$)/, ',');
}

dates = dates.sort((a, b) => {
  return Date.parse(replaceOrdinals(a)) - Date.parse(replaceOrdinals(b))
});

console.log(dates);

切记:

来自@adeneo 的评论:Date.parse 依赖于实现。您可能想要通读它的文档以确定时区之类的东西是否会把事情搞砸。作为更可靠的方法,您可以使用类似 moment.js 的日期解析。

中的解决方案很优雅,但它的应用仅限于ES6浏览器,实现date.parse()符合OP使用的特定日期格式。

不是为了避免 date.parse() 依赖而添加 moment.js 之类的库,而是可以制作一个可以在任何 JavaScript 环境(包括旧浏览器)中工作的定制解决方案只需几行代码:

var dates = [
  {'August 17th 2016': [75]}, 
  {'August 1st 2016': [5]}, 
  {'August 28th 2016': [5]}
];

dates.sort(function(a, b){
  var i, j;
  for(i in a); //get datestring a
  for(j in b); //get datestring b;
  return MMMDDYYYYtoSortableNumber(i) -
    MMMDDYYYYtoSortableNumber(j);
});

console.log(dates);

// MMMDDYYYYtoSortableNumber() converts datestrings
// such as "April 5th 1969" to 19690405.
// Month name to digit approach adapted from 
// https://gist.github.com/atk/1053863
  
function MMMDDYYYYtoSortableNumber(datestring) {
  var mdy = datestring.match(/\w(\w\w)\D+(\d+)\D+(\d+)/);
  return mdy[3] * 10000 +
    '  anebarprayunulugepctovec'.search(mdy[1]) * 50 +
    mdy[2] * 1;
}

请注意,将日期字符串表示为对象值而不是对象键可能更安全。然后它们将更容易安全地提取(并且访问速度更快)。例如

{label: 'August 17th 2016', data: [75]},