var comparator = function(a, b) {
var aName = a.get('name'),
bName = b.get('name'),
aParentId = a.get('parentId'),
bParentId = b.get('parentId');
if(!aParentId || !bParentId || aParentId == bParentId) {
// In these 3 cases, name has precedence
if(aName < bName) {
return -1;
}
else if(aName > bName) {
return 1;
}
else {
return 0;
}
} else if(aParentId < bParentId) {
return -1;
} else /* aParentId > bParentId */ {
return 1;
}
};
编辑:更正。必须考虑两个排序级别,记住任何缺少的 parentId 等于 parentIds。
您还可以将其实现为字段列表/定制比较器,这些比较器一个接一个地执行,下一个比较器在当前找到相等时被委派给。
var loopedComparator = function(a, b) {
var fields = [
{
name: 'parentId',
comparator: function(a, b) {
return (!a || !b || a == b) ? 0 : (a < b) ? -1 : 1;
}
},
{
name: 'name',
comparator: function(a, b) {
return (a == b) ? 0 : (a < b) ? -1 : 1;
}
}
];
var i, result = 0;
for(i in fields) {
var field = fields[i];
result = field.comparator(a.get(field.name), b.get(field.name));
if(result !== 0) {
return result; // On inequality we return right away
}
// Else we continue, delegating the comparison to the next field / comparator
}
// When the loop is done, or if fields was defined empty, we return the last equality
return result;
};
当然,使用此方案,您可以添加任意数量的列,并为每个列定义自定义比较器。