[英]sort array of objects to place a particular object first that matches an id
I have an array of objects that contain user data.我有一个包含用户数据的对象数组。
What I need to do is order them with the logged-in user first.我需要做的是先用登录用户订购它们。
I previously had this working with:我以前有这个工作:
const loggedInUserTemplate = users?.find(loggedInUser => {
return loggedInUser.id === user?.id;
});
renderUsers?.forEach((item, i) => {
if (item.id === loggedInUserTemplate.id) {
renderUsers?.splice(i, 1);
renderUsers?.unshift(item);
}
});
but for various reasons, I can't use this anymore.但由于各种原因,我不能再使用它了。
My new solutions include these but none work.我的新解决方案包括这些但没有工作。 Does anyone have any suggestions?有没有人有什么建议?
const loggedInUser = user?.id;
let test = JSON.parse(JSON.stringify(users));
// test = test.sort((a, user) => (a.id === loggedInUser ? 0 : 1));
// test = test.sort((a, user) => (a.id == loggedInUser ? 0 : 1));
test.sort((a, loggedInUser) => {
console.log("what is a?", typeof a.id, a.id);
console.log("user -----", typeof loggedInUser, loggedInUser);
if (a?.id === loggedInUser) return 0;
});
console.log("test", test);
The array looks like this:数组如下所示:
[
{__typename: "user", id: "4274", firstName: "tom"},
{__typename: "user", id: "742", firstName: "richard"},
{__typename: "user", id: "4293", firstName: "harry" }
]
In my test case the logged-in user id is "742", so I want "richard" to appear first in the array.在我的测试用例中,登录用户 id 是“742”,所以我希望“richard”首先出现在数组中。
Using the JavaScript built-in sort
method is the way to go, I agree.使用 JavaScript 内置sort
方法是 go 的方式,我同意。
Say you have an array of logged in user ids, let loggedInUsers = ["742"]
in your example.假设您有一个登录用户 ID 数组,在您的示例中设置为let loggedInUsers = ["742"]
。 Then sorting them like this should work:然后像这样对它们进行排序应该可以工作:
test.sort((a, b) => {
// push b to the top if he is logged in
if(loggedInUsers.includes(b.id)) return 1;
// otherwise stick to the original order
else return 0;
})
Meaning if the first user (of a and b) is logged in, it gets pushed to the top.这意味着如果第一个用户(a 和 b)登录,它将被推到顶部。 You could change the if statement to keep the original order of logged in users by only pushing b up if a is not logged in:如果 a未登录,您可以通过仅将 b 向上推来更改 if 语句以保持登录用户的原始顺序:
if(loggedInUsers.includes(b.id) && !loggedInUsers.includes(a.id)) return 1;
So the solution was to create a new array in state and use .sort()
like this.所以解决方案是在 state 中创建一个新数组并像这样使用.sort()
。
setUserArray([...users].sort(a => (a.id === user.id? -1: 1)));
*Note the -1 as chrome reads a 0 as falsy so it won't work like that. *注意 -1 因为 chrome 将 0 读取为 falsy,所以它不会那样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.