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?

5
  • var validRoles = ["Role1", "Role"]; last element typo: Role2 Commented Aug 18, 2016 at 14:03
  • 1
    data is already an array and validRoles is another array. That's not how indexOf works. Commented Aug 18, 2016 at 14:04
  • Just use userInValidRole = data.indexOf(role1) > -1 || data.indexOf(role2) > -1; Commented Aug 18, 2016 at 14:04
  • data could have multiple roles, right? So if the user has role1 and role3, you're searching the list ['Role1', 'Role3'] to see if any of the elements are equal to the entire list ['Role1', 'Role']. Commented Aug 18, 2016 at 14:05
  • You need to check validRoles.indexOf() for each value in data Commented Aug 18, 2016 at 14:06

2 Answers 2

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()...)

Sign up to request clarification or add additional context in comments.

1 Comment

If userInValidRole should be false otherwise, you could simplfify this: `userInValidRole = data.some(function(r) { return validRoles.indexOf(r) > -1; });
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

2 Comments

This works and I did it for quite some time before learning of Array.prototype.some
Nice! I didn't know about Array.prototype.some, good to know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.