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

617 views Asked by At

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;
        }
3

There are 3 answers

0
Glitcher On BEST 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;
    }
}
0
Abiodun On

Use this. no need of underscore you can use .some array

USER_ROLES.some(function(value){
 return value.substring(0, 5) === "ROLE_";
});
0
Mohammed Akdim On
var index, value, result;
for (index = 0; index < USER_ROLES.length; ++index) {
    value = USER_ROLES[index];
    if (value.substring(0, 5) === "ROLE_") {
        // You've found it, the full text is in `value`.
        // So you might grab it and break the loop, although
        // really what you do having found it depends on
        // what you need.
        result = value;
        break;
    }
}

// Use `result` here, it will be `undefined` if not found