[英]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] },
...
]
按日期排序此數組中對象的最佳方法是什么,並保持其鍵的“英語”表示?
注意 :該鍵用作圖表標簽。
我到處都看array.sort
使用,但是這是在說的對象的關鍵created_at
。
結果應該是:
[
{ 'August 1st 2016': [5] },
{ 'August 17th 2016': [75] }
{ 'August 28th 2016': [5] },
...
]
我不知道該怎么辦,所以我沒有什么可展示的 。
這可以通過在對象鍵上使用date.parse
來完成。 我拿了第一個對象鍵,因為它看起來在數組的每個條目中只有1個。 最棘手的部分是date.parse
不會對“12”或“1”的工作,所以,我們不得不暫時取代“日”或“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);
記住:
來自@adeneo的評論: Date.parse
是依賴於實現的。 您可能希望閱讀它的文檔,以確定時區之類的東西是否會搞砸。 作為一種更確定的方法,您可以使用類似moment.js的東西進行日期解析。
Kevbot的答案中的解決方案很優雅,但其應用程序僅限於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]},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.