2017-04-26 74 views
-1

我想按三個值排序此JavaScript數組,但我似乎無法弄清楚如何一次對多個屬性進行排序。按3個值對JavaScript數組進行排序

的要求是:

  1. featured項目應該是在最高層
  2. 然後項目進行沒有名(null
  3. 然後用姓名的項目是featured
  4. createdAt降序排序(從最新的優先排序)

這是數組:

var items [ 
    { name: 'foo-1', featured: true, createdAt: 1493000001 }, 
    { name: null, featured: false, createdAt: 1493000003 }, 
    { name: 'foo-3', featured: true, createdAt: 1493000002 }, 
    { name: 'foo-4', featured: false, createdAt: 1493000004 }, 
    { name: 'foo-5', featured: false, createdAt: 1493000005 }, 
]; 

結果應該是:

[ 
    { name: 'foo-3', featured: true, createdAt: 1493000002 }, 
    { name: 'foo-1', featured: true, createdAt: 1493000001 }, 
    { name: null, featured: false, createdAt: 1493000003 }, 
    { name: 'foo-5', featured: false, createdAt: 1493000005 }, 
    { name: 'foo-4', featured: false, createdAt: 1493000004 }, 
] 
+3

已經回答[如何排序多個字段對象數組?](HTTP的=> http://stackoverflow.com/a/4760279/1315419 – Vasan

+4

可能重複:/ /stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) –

+0

@Vasan是的,這個答案真的很好 - http://stackoverflow.com/a/ 4760279/2957677 –

回答

2

var items = [ 
 
    { name: 'foo-1', featured: true, createdAt: 1493000001 }, 
 
    { name: null, featured: false, createdAt: 1493000003 }, 
 
    { name: 'foo-3', featured: true, createdAt: 1493000002 }, 
 
    { name: 'foo-4', featured: false, createdAt: 1493000004 }, 
 
    { name: 'foo-5', featured: false, createdAt: 1493000005 }, 
 
]; 
 

 
items.sort(function(a, b) { 
 
    if(a.featured && !b.featured) return -1; // if a is featured and b is not, then put a above b 
 
    if(!a.featured && b.featured) return 1; // if b is featured and a is not, then put b above a 
 
    
 
    if(!a.name && b.name) return -1;   // if a doesn't have a name and b does, then put a above b 
 
    if(a.name && !b.name) return 1;   // if b doesn't have a name and a does, then put b above a 
 
    
 
    return b.createdAt - a.createdAt;  // otherwise (a and b have simillar properties), then sort by createdAt descendently 
 
}); 
 

 
console.log(items);

1

你可以使用一個比較,可以作爲參數傳遞給sort()函數傳遞功能 - 有關更多詳細信息,請參閱Array.prototype.sort()。你的情況比較函數可能看起來像這樣:

var items = [ 
    { name: 'foo-1', featured: true, createdAt: 1493000001 }, 
    { name: null, featured: false, createdAt: 1493000003 }, 
    { name: 'foo-3', featured: true, createdAt: 1493000002 }, 
    { name: 'foo-4', featured: false, createdAt: 1493000004 }, 
    { name: 'foo-5', featured: false, createdAt: 1493000005 }, 
]; 

function compare(a, b) { 
    if (a.featured === true && b.featured === false) return -1; 
    if (a.featured === false && b.featured === true) return 1; 
    if (a.name === null && b.featured !== null) return -1; 
    if (a.name !== null && b.name === null) return 1; 

    return b.createdAt - a.createdAt; 
}; 

items.sort(compare); 

應該覆蓋情況下,當是一個空字符串。

相關問題