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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With