Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurances in string from keyword array in javascript

I have an array:

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

and a string:

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

I want to count the number of times each keyword in the array appears in the string but can't figure out the best way to do that.

like image 212
StefanHayden Avatar asked May 01 '26 05:05

StefanHayden


1 Answers

Here is 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 out here.

like image 128
Chris Nielsen Avatar answered May 02 '26 19:05

Chris Nielsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!