Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, return all the indexes that match substrings in original array;

I have an array that I wish to return the indexes in a new array if the original array matches a substring.

Currently I am coding it like this:

tv_show = ["bbc1_7.30","bbc1_8.00","itv1_8.40","bbc1_10.00"];
    indexesFromSearch = [];

tv_show.forEach(function(elem, index, array){
    a0 = tv_show[index].substring(0,5);
    if(a0=="bbc1_"){ 
        indexesFromSearch.push(index);
    };
    return indexesFromSearch;
});

alert(indexesFromSearch);

It works fine but just wondered if there is a better way to code it.

Thanks.

like image 270
Flash20 Avatar asked Feb 12 '26 13:02

Flash20


1 Answers

You could get the indices and filter with startsWith.

const
    tv_show = ["bbc1_7.30", "bbc1_8.00", "itv1_8.40", "bbc1_10.00"],
    indices = [...tv_show.keys()].filter(i => tv_show[i].startsWith('bbc1_'));

console.log(indices);
like image 122
Nina Scholz Avatar answered Feb 15 '26 02:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!