我想用三个值对这个JavaScript数组进行排序,但我似乎无法弄清楚如何一次按多个属性进行排序。
要求是:
featured
项目应位于最顶端null
)featured
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 },
]
答案 0 :(得分:3)
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 :(得分: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);
它应涵盖名称为空字符串的情况。