-2

I am trying to search through each element in an Array to find if it contains a substring. If it does I want to have the index returned.

Presently, I am using this code:

function searchString(){
    for(n=0; n<a0.length; n++){
        if(a0[n].substring(0,4)=="heat"){
            return n;
        }
    };
}

a0 = new Array("bbc_0","d","e","heat_","a","c");

a2 = searchString();
alert("heat APPEARS @ index: "+a2);

But unsure if this is the best way to go about it.

0

1 Answer 1

1

Try this

const arr = ["bbc_0","d","e","heat_","a","c"]
const index = arr.findIndex(i => i.includes("heat"))
console.log(index) //should be 3

1
  • Good point. Thanks!
    – dkostrzewa
    Commented Jul 19, 2021 at 21:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.