ibab ibab - 2 months ago 9
Javascript Question

JavaScript Finding if string in array can be found in an object

I have an object that includes different roles and I have an array that includes specific colors.

What I want to do, is see if the roles.name includes any of the strings in the colors array. I've tried different approaches, such as:

var colors = ["blue", "yellow", "brown", "red", "green", "pink", "purple"];
var roles = [{"name": "asd"},
{"name": "blue"},
{"name": "yellow"},
{"name": "brown"},
{"name": "red"},
{"name": "green"},
{"name": "pink"},
{"name": "purple"},
{"name": "fgh"},
{"name": "jkl"}];
for (var i = 0; i < roles.length; i++) {
if (roles[i].name.indexOf(colors)) {
console.log(roles[i].name);
}
}


And

var colors = ["blue", "yellow", "brown", "red", "green", "pink", "purple"];
var roles = [{"name": "asd"},
{"name": "blue"},
{"name": "yellow"},
{"name": "brown"},
{"name": "red"},
{"name": "green"},
{"name": "pink"},
{"name": "purple"},
{"name": "fgh"},
{"name": "jkl"}];
roles.forEach(role => {
if (role.name.indexOf(colors)) {
console.log(role.name);
}
});


But with both of the codes, the result is the full list of roles.

Expected result is all colors logged to the console. What I get is all roles logged to the console.

Answer

You're using indexOf backwards. It should be array.indexOf(valueToSearchFor), but you have valueToSearchFor.indexOf(array). Also, indexOf returns the index, not a boolean; to test whether the element is found, you have to compare it to -1.

var colors = ["blue", "yellow", "brown", "red", "green", "pink", "purple"];
var roles = [{"name": "asd"},
        {"name": "blue"},
        {"name": "yellow"},
        {"name": "brown"}, 
        {"name": "red"},
        {"name": "green"},
        {"name": "pink"},
        {"name": "purple"},
        {"name": "fgh"},
        {"name": "jkl"}];
for (var i = 0; i < roles.length; i++) {
  if (colors.indexOf(roles[i].name) != -1) {
    console.log(roles[i].name);
  }
}