如果缺少任何字段,如何对数组进行如下排序?
例如,现有数组为:
const users = [
{
id: 1, firstname: 'Jerry'
}, {
id: 2, firstname: 'Thomas', lastname: 'Geib'
}, {
id: 3
}, {
id: 4, lastname: 'Berg'
}, {
id: 5, firstname: 'Ass', lastname: 'Noob'
}, {
id: 6, lastname: 'Jopa'
}
]
,结果应按以下顺序排序:
firstname
和lastname
的对象firstname
或lastname
的对象firstname
和lastname
的对象看起来像这样:
const users = [
{
id: 2, firstname: 'Thomas', lastname: 'Geib'
}, {
id: 5, firstname: 'Ass', lastname: 'Noob'
}, {
id: 1, firstname: 'Jerry'
}, {
id: 4, lastname: 'Berg'
}, {
id: 6, lastname: 'Jopa'
}, {
id: 3
}
]
我已经尝试过这种排序,但结果不是我需要的
users.sort((a,b) => {
if (a.firstname === b.firstname) {
return 0
}
if (!a.firstname) {
return 1
}
return -1
});
答案 0 :(得分:6)
您可以通过检查属性是否存在来进行排序。最后按id
升序排序。
const users = [{ id: 1, firstname: 'Jerry' }, { id: 2, firstname: 'Thomas', lastname: 'Geib' }, { id: 3 }, { id: 4, lastname: 'Berg' }, { id: 5, firstname: 'Ass', lastname: 'Noob' }, { id: 6, lastname: 'Jopa' }];
users.sort((a, b) =>
('firstname' in b && 'lastname' in b ) - ('firstname' in a && 'lastname' in a) ||
('firstname' in b) - ('firstname' in a) ||
('lastname' in b) - ('lastname' in a) ||
a.id - b.id
);
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
好吧,只需计算每一项所具有的属性数量并按该数字排序,降序为:
var users = [
{id: 1,firstname: 'Jerry'},
{id: 2,firstname: 'Thomas', lastname: 'Geib'},
{id: 3},
{id: 4,lastname: 'Berg'},
{id: 5,firstname: 'Ass',lastname: 'Noob'},
{id: 6,lastname: 'Jopa'}
];
users.sort(function(a, b) {
var aw = ('firstname' in a) + ('lastname' in a);
var bw = ('firstname' in b) + ('lastname' in b);
return bw - aw;
});
console.log(users);