Jay Jay - 6 months ago 31
Javascript Question

How to check a Javascript array that contains at least one value that starts with a particular text (eg. ROLE_)

I have the below javascript 'underscore' code which checks if the given USER_ROLES has at least one VALID_ROLES. If so returns true else false.
It works fine.

But I want to refactor it such that I want to remove the hard coded roles VALID_ROLES and want to check if there is at least one role that starts with ROLE_. How can it be done ?

// Function to check if least one valid role is present
var USER_ROLES = ['ROLE_5'];

function hasAnyRole(USER_ROLES) {

var VALID_ROLES = [ 'ROLE_1', 'ROLE_2', 'ROLE_3', 'ROLE_4' ];

for (var i = 0; i < USER_ROLES.length; i++) {
if (_.contains(VALID_ROLES, USER_ROLES[i])) {
console.log("Found a valid role, returning true.");
return true;
}
}
console.log("No valid role found, returning false.");
return false;
}

Answer

You're pretty close, but for what you want there's no need to use underscore:

for (var i = 0; i < USER_ROLES.length; i++) {
    if (typeof USER_ROLES[i].indexOf == "function" && USER_ROLES[i].indexOf("ROLE_") > -1) {
        console.log("Found a valid role, returning true.");
        //return true;
    }
}