1

Not sure how to explain this in words, but is there any function in javascript that, when given a string , will return the number of times it occurs in an array?

For example:

var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.count("c");

With repeats then being equal to 3 as "c" occurs 3 times. I tried to look this up but I wasn't sure on how to word it so I didn't get anything useful.

4 Answers 4

3

You can create your own function or add it to the prototype of Array:

Array.prototype.count = function (val){ 
      var result = 0;
      for(var i = 0; i < this.length; i++){
        if(this[i] === val) result++;
      }

      return result;
}

Then you can do ['a','b', 'a'].count('a') // returns 2

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array.filter()

var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.filter(function(value) { return value==="c"; } ).length;
console.log(repeats)

Comments

0
arr.filter(function(v){return v=='c';}).length

Comments

0

Exact Word Match Example

var search_word = 'me';
var arr = ['help','me','please'];
arr.filter(function(el){return el === search_word}).length;

The filter function will return the element if the result of the function is true. The function is called on each element of the array. In this case, we are comparing the array element to our search word. If they are equal (true) the element is returned. We end up with an array of all the matches. Using .length simply gives us the number of items in the resulting array; effectively, a count.

Partial Match Example

If you were to want something a little more robust, for instance count the number of words that contain the letter l, then you could tokenize the string and scan the index, or use some regex which is a little more costly, but also more robust:

var search_word = 'l';
var arr = ['help','me','please'];
arr.filter( function(el){ return ( el.match(search_word) || [] ).length }).length;

Note that match also returns an array of matching elements, but an unsuccessful match returns undefined and not an empty array, which would be preferred. We need an array to use .length (the inside one), otherwise it would result in an error, so we add in the || [] to satisfy the case when no matches are found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.