Ctrl_Alt_Defeat
Ctrl_Alt_Defeat

Reputation: 4009

Check array for values javascript

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?

Upvotes: 2

Views: 72

Answers (2)

blex
blex

Reputation: 25634

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

Upvotes: 5

mkaran
mkaran

Reputation: 2718

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

Upvotes: 0

Related Questions