2

I have the following in my angular controller

MyUserService.getUserRoles().then(function (data) {
    var userInValidRole = false;
    var role1 = "Role1";
    var role2 = "Role2";

    if ((data.indexOf(role1) > -1) || data.indexOf(role2 ) > -1) {
        userInValidRole = true;
    }

This is working as expected. However I was hoping to do something like:

var validRoles = ["Role1", "Role"];

and then check

    if ((data.indexOf(validRoles) > -1)) {
        userInValidRole = true;
    }

However it is not working as expected - is there something I have done wrong?

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116

2 Answers2

5

You can use Array.prototype.some to check if any role in data is a validRole. And, as @adam-beck suggested below, you cen get rid of the if statement:

var validRoles = ['Role1', 'Role2'],
    userInValidRole = data.some(function(r){ return validRoles.indexOf(r) > -1; });

The advantage of that method is performance. As soon as it finds a correct value, it stops the loop (unlike .forEach(), .map(), .filter()...)

blex
  • 24,941
  • 5
  • 39
  • 72
  • 1
    If userInValidRole should be false otherwise, you could simplfify this: `userInValidRole = data.some(function(r) { return validRoles.indexOf(r) > -1; }); – adam-beck Aug 18 '16 at 14:17
0

Check array intersection mentioned in this post Simplest code for array intersection in javascript

if(data.filter(function(n) {
    return validRoles.indexOf(n) != -1;
}).length > 0){
userInValidRole = true;
}

note: if you want the user to have both roles then check for length == validRoles.length

Community
  • 1
  • 1
mkaran
  • 2,528
  • 20
  • 23