1

This must be so simple, yet I can't quite figure out how to count the number of substrings within an array of things. Anything in Underscore for this that I'm missing?

var foo = ["fred", "ted", "medical", "car"]

function howManySubstringsInArray(arr, word){
    var i = arr.length,
    j = 0;
    while (i) if (arr[--i].indexOf(word))++j;
    return j;
}

howManySubstringsInArray(foo, 'ed')
Output => 3

This isn't working.

Hairgami_Master
  • 5,429
  • 10
  • 45
  • 66

3 Answers3

6

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;
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
3

Your while loop needs to check the actual index.

 while (i) if (arr[--i].indexOf(word) !== -1) ++j;

You could also use reduce well here:

function howManySubstringsInArray(arr, word){
  return _.reduce(arr, function(count, val){
    return count + (val.indexOf(word) === -1 ? 0 : 1)
  }, 0);
}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
-1
function howManySubstringsInArray(arr,str)
{
var count=0;
   $.each(arr,function(i,item)){
   if(item.indexOf(str)!=-1)
    {
      count ++;
    }
  });
 return count;
}

Change $.each to for if you want.

Anh Tú
  • 636
  • 7
  • 21