按3个值对JavaScript数组排序

Til*_*ill 0 javascript arrays sorting

我想按三个值对这个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 },
];
Run Code Online (Sandbox Code Playgroud)

结果应为:

[
    { 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 },
]
Run Code Online (Sandbox Code Playgroud)

ibr*_*rir 5

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);
Run Code Online (Sandbox Code Playgroud)