Assuming that you don't care about repeated matches within each array element, you can filter
the array to find matching elements:
NB: this is a standard ECMAScript 5 function, not from underscore. There's a shim for older browsers at the above link.
function howManySubstringsInArray(arr, word) {
return arr.filter(function(v) {
return v.indexOf(word) >= 0;
}).length;
}
Strictly speaking this is creating a new array which is slightly wasteful since all we're doing is counting the elements, but for "small" lists it won't matter.
A bare loop would actually work pretty well anyhow - you just need to make sure the loop is structured correctly, and that you actually look at the result of the .indexOf
call. Your existing backwards iteration makes the loop conditions far harder to follow than they need to be:
function howManySubstringsInArray(arr, word) {
var i = 0, n = arr.length, count = 0;
for ( ; i < n; ++i) {
if (arr[i].indexOf(word) >= 0) {
++count;
}
}
return count;
}