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?

share|improve this question
1  
Perhaps roles.filter(role => role.groups.find(group => user.groups.includes(group.id))) – Xotic750 Sep 20 '16 at 18:15
1  
Also you have defined const roles and then you try to redefine it. – Xotic750 Sep 20 '16 at 18:35
    
Thanks for the .includes ;) – jdsninja Sep 20 '16 at 18:50
up vote 1 down vote accepted

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.