HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Filter array with another array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayanotherfilterwith

Problem

I want to output only the roles that contain the same group as the user.



// User can be part of many groups
const user = {
groups: ["group2"]
};

// Roles can have many groups
// What you see here is the output or 2 different data source
// Thats why we have group duplication inside different role
const roles = [{
name: "role1",
groups: [{
id: "group1"
}]
}, {
name: "role2",
groups: [{
id: "group1"
}, {
id: "group2"
}]
}];

const result = roles.filter(role => role.groups.filter(group => user.groups.indexOf(group.id) > -1).length)
console.log(result);




Is there a better way by using reduce or something else?

Solution

This is little neater IMO.



// User can be part of many groups
const user = {
groups: ["group2"]
};

// Roles can have many groups
// What you see here is the output or 2 different data source
// Thats why we have group duplication inside different role
const roles = [{
name: "role1",
groups: [{
id: "group1"
}]
}, {
name: "role2",
groups: [{
id: "group1"
}, {
id: "group2"
}]
}];

const result = roles.filter(role => role.groups.find(group => user.groups.includes(group.id)));
console.log(result);

Context

StackExchange Code Review Q#141943, answer score: 7

Revisions (0)

No revisions yet.