gpt4 book ai didi

javascript - 基于Javascript中的多个条件对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 20:39:48 25 4
gpt4 key购买 nike

我有一个包含对象的数组,如下所示:

[{
id: 34,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'Steven',
age: 24
}]
} ,{
id: 35,
users: [{
name: 'John',
age: 23,
}, {
name: 'Steven',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 36,
users: [{
name: 'Lisa',
age: 23,
}, {
name: 'John',
age: 24
}, {
name: 'Homer',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 37,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}]
}]

我想根据几个条件(优先)对数组进行排序:首先,我想要用户名称为“John”和“Lisa”且用户数小于 3 的对象其次,我想要对象的用户名称为“John”和“Lisa”,而不管参与者的数量然后剩下的对象

因此,我举的例子中的数组将变为:

[{
id: 37,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}]
}, {
id: 36,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}, {
name: 'Homer',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 34,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'Steven',
age: 24
}]
}, {
id: 35,
users: [{
name: 'John',
age: 23
}, {
name: 'Steven',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}]

我现在有这个,它根据参与者的姓名和数量正确排序。但是如果参与者的数量不匹配,那么它就不会关心要排序的名字,这是错误的:

 const names = ['John', 'Lisa']
unorderedLeagues.sort((a, b) => {
const aUserIncluded = every(names, priorityName =>
some(a.users, { name: priorityName }),
);
const bUserIncluded = every(names, priorityName =>
some(b.users, { name: priorityName }),
);

return (
(bUserIncluded && b.users.length <= 3) -
(aUserIncluded && a.users.length <= 3)
);
});

我应该如何修改此排序以执行我描述的优先级类型?

最佳答案

您可以使用 bool 值来检查所需名称是否在 users 中。然后取长度为好还是不取。

var array = [{ id: 34, users: [{ name: 'John', age: 23}, { name: 'Steven', age: 24}] }, { id: 35, users: [{ name: 'John', age: 23}, { name: 'Steven', age: 24}, { name: 'Charlie', age: 24}] }, { id: 36, users: [{ name: 'Lisa', age: 23}, { name: 'John', age: 24}, { name: 'Homer', age: 24}, { name: 'Charlie', age: 24}] }, { id: 37, users: [{ name: 'Lisa', age: 23}, { name: 'John', age: 24}] }],
find = ['John', 'Lisa'];

array.sort(function (a, b) {
var aAll = find.every(n => a.users.find(({ name }) => name === n)),
bAll = find.every(n => b.users.find(({ name }) => name === n));

return (bAll && b.users.length === 2) - (aAll && a.users.length === 2) || bAll - aAll;
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 基于Javascript中的多个条件对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49404677/

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