gpt4 book ai didi

javascript - 根据对象中字段的存在对数组进行排序

转载 作者:行者123 更新时间:2023-11-28 11:29:57 26 4
gpt4 key购买 nike

如果缺少任何字段,如何对如下所示的数组进行排序?

例如,现有数组是:

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'
}
]

结果应按以下顺序排序:

  1. 具有名字姓氏的对象
  2. 仅包含名字姓氏的对象
  3. 不带名字姓氏的对象

这样它看起来像:

    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
});

最佳答案

您可以通过检查该属性是否存在来排序。最后按 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; }

关于javascript - 根据对象中字段的存在对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54421398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com