My program currently loops through an array and counts the amount of times a pattern occurs in all of them together.
For example: if I should search “at” at prompt I will end up with:
0,1,2,3,4
But really I want to end up with
4,1
As at appears 4 times in array 1 and once in array 2.
This being the amount of times the pattern occurs in the array.
Any advice on how I can achieve this?
Many thanks in advance!
web = ["cat fat hat mat", "that the who"];
var search = prompt('Search?');
function count(web, pattern)
{
if (pattern)
{
var num = 0;
var result = [];
for (i = 0; i < web.length; i++)
{
var current = web[i];
var index = current.indexOf(pattern);
while (index >= 0)
{
result[result.length] = num++;
index = current.indexOf(pattern, index + 1);
}
}
return result;
}
else
{
return ("Nothing entered!");
}
}
alert(count(web, search));
This works too