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.
4
Answers
You could get the indices and filter with
startsWith
.you can use
includes
like this:The simplest way to achieve this is to
reduce
the array. This is essentially a combination offilter
andmap
.Here is a concise version with a reusable helper:
You can use
reduce
andstartsWith
: