[英]Sort JavaScript array by 3 values
I'd like to sort this JavaScript array by three values, but I can't seem to figure out how to sort by more than one property at a time. 我想按三个值对这个JavaScript数组进行排序,但是我似乎无法弄清楚如何一次按多个属性进行排序。
The requirements are: 要求是:
featured
items should be at the very top featured
商品应放在最顶端 null
) null
) featured
featured
createdAt
in descending order (newest first) createdAt
的降序对所有内容进行排序( createdAt
到旧) This is the array: 这是数组:
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 },
];
The result should be: 结果应为:
[
{ 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 },
]
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);
You can use a compare function which can be passed as an argument to the sort() function - see Array.prototype.sort() for more detailed information. 您可以使用一个比较函数,该函数可以作为参数传递给sort()函数-有关更多详细信息,请参见Array.prototype.sort() 。 In your case the compare function may look like this:
在您的情况下,compare函数可能如下所示:
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);
It should cover the case when the name is an empty string. 当名称是一个空字符串时,它应该涵盖这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.