Count counts per string from array of keywords in javascript

I have an array:

var locations = ['Afghanistan','Albania','Algeria','New York'];

      

and the line:

var string = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';

      

I want to count the number of times each keyword in an array appears in a row, but cannot find a better way to do it.

+2


source to share


4 answers


Here's my version:

function countItems(a, s) {
    var x, i, output = {};
    for (x = 0; x < a.length; x++) {
        i = 0;
        output[a[x]] = 0;
        while ((i = s.indexOf(a[x], i)) > -1) {
            output[a[x]]++;
            i++
        }
    }
    return output;
}

var result = countItems(locations, string);
// result['Albania'] === 0

      



Try it here .

+5


source


Try something like this. You can change what you are doing from count

- store it in another array, display it (which is what this script does), etc.



var locations = ['Afghanistan','Albania','Algeria','New York'];
var str = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';


for(var i=0; i<locations.length; i++) {
    var pattern = new RegExp(locations[i], "g");
    var m = str.match(pattern);
    if (m != null)
    {
       var count = m.length; // the count
       alert("There are " + count + " occurrences of " + locations[i]);
    }
}

      

+4


source


<script language="JavaScript">
var locations = ['Afghanistan','Albania','Algeria','New York'];

var string1 = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';

for (var i=0;i<locations.length;i++) {
  nCount = string1.split(locations[i]).length-1;
  document.write(locations[i] + ' is found ' + nCount + ' times<br>');
}

</script>

      

+1


source


This code only instantiates one object RegExp

and uses the reverse while-loop. I'm sure this is as fast as you can go without breaking the laws of physics :)

This is what happens:

  • Construct regex string with reverse while-loop
  • Create only one RegExp object and match()

    it's on a line
  • Count the length of the array returned by the function match()

Here's the implementation:

var countries = ["Afganistan", "America", "Island"];
var sentence = "I love Afganistan, America.. And I love America some more";

function countOccurrences(a, s)
{
    var re = "",
        l = a.length,
        m;

    while (l)
    {
        l--;

        re += a[l];

        if (l > 0) re += "|";
    }

    m = s.match(new RegExp(re, "gi")) || [];

    return m.length;
}

      

Note. I would of course expect the entries in the array to be sanitized for any special characters that would ruin the regex built inside the function.

var occurrences = function countOccurrences(countries, sentence); // returns 3

      

+1


source







All Articles