Reputation: 1850
I am trying to compare 2 arrays of objects, and to check if 1 array has all elements with the same id
and role
of the other array. The arrays look like this:
const allUsers = [
{ id: 1, roleId: 123, username: 'User1', roles:['admin'] }
{ id: 2, roleId: 123, username: 'User2', roles:['admin'] }
{ id: 3, roleId: 123, username: 'User3', roles:['admin'] }
{ id: 4, roleId: 123, username: 'User4', roles:['admin'] }
{ id: 5, roleId: 233, username: 'User5', roles:['admin'] }
]
// first example - here I have to return false
const selectedUsers = [
{ id: 1, roleId: 123, username: 'User1', roles:['admin'] }
{ id: 2, roleId: 123, username: 'User2', roles:['admin'] }
{ id: 5, roleId: 233, username: 'User5', roles:['admin'] }
]
// 2nd example - here I can return true
const selectedUsers = [
{ id: 1, roleId: 123, username: 'User1', roles:['admin'] }
{ id: 2, roleId: 123, username: 'User2', roles:['admin'] }
]
What I need is the following - here in selectedUsers
I have selected all users with roleId: 233
and roles:['admin']
, so I would need to set some flag to false. If i didn't have that user, If I just had users 1/2 with roleId: 123
, I could delete them because there are more users with the same roleId and roles: ['admin']
I need to compare these arrays somehow and check if all users with same roleId
and role
are trying to be removed.
Any tips on what would be the easiest solution?
EDIT: As i wrote in the comment, I am trying to check if I can remove the selectedUsers
, but i can do that only if there is at least 1 different user left with the same roleId and 'admin' in allUsers
array
Upvotes: 0
Views: 89
Reputation: 1482
You can return this in your function:
return selectedUsers.every(u =>
allUsers.filter(a =>
a.roleId === u.roleId && a.roles.join('') === u.roles.join(''))
.length > 1);
every()
makes sure every selectedUser
satisfies a conditionfilter()
which makes sure that you need to have at least 2 similar users with the same roleId
and roles
as the user being checked. Note that it's 2 not 1, as allUsers
also currently includes the user being checked, which will be potentially deleted after you return true
from this function.join()
trick does a simple deep-equal comparison of two roles
arrays (you can't just check u.roles == a.roles
) provided that the roles should be listed in a consistent order (in case of more than one roles).Upvotes: 1