admin管理员组

文章数量:1398984

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.

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.

Share Improve this question asked Mar 28, 2013 at 15:15 Hairgami_MasterHairgami_Master 5,53911 gold badges46 silver badges66 bronze badges 3
  • Check out: stackoverflow./questions/4009756/… – John K. Commented Mar 28, 2013 at 15:18
  • 2 Should it match multiple substrings in one word? – loganfsmyth Commented Mar 28, 2013 at 15:20
  • you should use arr[--i].indexOf(word) != -1 – jcubic Commented Mar 28, 2013 at 15:21
Add a ment  | 

3 Answers 3

Reset to default 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;
}

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);
}
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.

本文标签: