2013-10-17 53 views
30

我想排序的對象包含如何通過日期

var recent = [{id: "123",age :12,start: "10/17/13 13:07"} , {id: "13",age :62,start: "07/30/13 16:30"}]; 

日期格式的每個對象的數組排序對象的JavaScript數組是:mm/dd/yy hh:mm

我想日期的順序排序與最新的第一。如果日期相同,則應該按時排序。

我嘗試了下面的排序功能。但它不起作用。

recent.sort(function(a,b)) 
{ 
    a = new Date(a.start); 
    b = new Date(b.start); 
    return a-b; 
}); 

另外我應該如何迭代通過對象進行排序?例如:

for (var i = 0; i < recent.length; i++) 
    { 
     recent[i].start.sort(function (a, b) 
     { 
      a = new Date(a.start); 
      b = new Date(b.start); 
      return a-b; 
     }); 
    } 

數組中可以有任意數量的對象。

+1

您的'最近的'文字是錯誤的。 –

+2

第一個塊無效javascript – SheetJS

+1

最近是我的數組對象的名稱。你能否詳細說明一下? – Anthea

回答

49

正如已經在評論中指出的那樣,最近的定義是不正確的javascript。

不過,假設日期是字符串:

var recent = [ 
    {id: 123,age :12,start: "10/17/13 13:07"}, 
    {id: 13,age :62,start: "07/30/13 16:30"} 
]; 

然後排序是這樣的:

recent.sort(function(a,b) { 
    return new Date(a.start).getTime() - new Date(b.start).getTime() 
}); 

More details on sort function from W3Schools

+1

你可以在這裏找到這個主題的一些有用的答案:** [按日期排序JavaScript對象數組] **(http://stackoverflow.com/a/26759127/2247494)** – jherax

+1

** note **:別忘了顯式'返回'聲明 – pruett

+2

我認爲你不需要'getTime()'或不需要 –

5
recent.sort(function(a,b) { return new Date(a.start).getTime() - new Date(b.start).getTime() }); 
+3

根據參數之間的關係,比較函數應該返回負值,0或正值,而不是布爾值。 – Barmar

+0

看起來很棒,我已經更新了我的答案。 –

+0

減去Date對象顯然會返回與減去它們的'getTime()'值相同的東西,儘管我無法在任何規範中找到此要求。 – Barmar

0

此功能允許您創建一個比較,將步行路徑您想要比較的關鍵字:

function createDateComparator (path = [] , comparator = (a, b) => a.getTime() - b.getTime()) { 
 
    return (a, b) => { 
 
    let _a = a 
 
    let _b = b 
 
    for(let key of path) { 
 
     _a = _a[key] 
 
     _b = _b[key] 
 
    } 
 
    return comparator(_a, _b) 
 
    } 
 
} 
 

 

 
const input = (
 
    [ { foo: new Date(2017, 0, 1) } 
 
    , { foo: new Date(2018, 0, 1) } 
 
    , { foo: new Date(2016, 0, 1) } 
 
    ] 
 
) 
 

 
const result = input.sort(createDateComparator([ 'foo' ])) 
 

 
console.info(result)