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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With