Doug Fir Doug Fir - 4 months ago 10
Javascript Question

How do I get the index of an array where it contains a string?

var qs = ["color=green", "pet=dog", "fruit=apple]


I want to get fruit. Tried:

for (var j=0; j<qs.length; j++) {qs[j].indexOf('fruit')}


That returned 0.

I expected it to return 2, the last entry int he array? How do I find which array value is the one I want?

Answer

You almost got it, you need to do a break on the index or make a new array and push the ones with matching indexes into that array

var arr = [];

for (var j=0; j<qs.length; j++) 
{
    if(qs[j].indexOf('fruit')!==-1){
        arr.push(j);
    }
}
//print all the indexes that contain fruit
for(var i in arr)
console.log(arr[i]);

If you just want one index just break

var matchingIdx=-1;
for (var j=0; j<qs.length; j++) 
{
    if(qs[j].indexOf('fruit')!==-1){
       matchingIdx = j;
       break;
    }
}

and if you want to generalize this can put it into a function

function gettingMatchingIndexes(qs, target) {
    var arr = [];
    for (var j=0; j<qs.length; j++) 
    {
        if(qs[j].indexOf(target)!==-1){
            arr.push(j);
        }
    }
    return arr;
}