Ctrl_Alt_Defeat Ctrl_Alt_Defeat - 1 year ago 53
Javascript Question

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?

Answer Source

You can use Array.prototype.some to check if any role in data is a validRole. And, as @adam-back 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()...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download