So I’ve edited my code a bit and I’m stuck trying to the count the number of times a pattern occurs in a specified record.
I would like the array to return as 2,1,0 if something like in is searched but currently all I get is 13,19,-1.
I would really appreciate any hints on how to improve my code.
books = [
{
title: "Inheritance: Inheritance Cycle, Book 4",
author: "Christopher Paolini",
},
{
title: "The Sense of an Ending",
author: "Julian Barnes"},
{
title: "Snuff Discworld Novel 39",
author: "Sir Terry Pratchett",
}
]
search = prompt("Title?");
function count(books, pattern) {
var num = 0;
var result = [];
for (i = 0; i < books.length; i++) {
var index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase());
do {
result[i] = index;
index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1);
}
while (index >= 0)
num = 0;
}
return result;
}
alert(count(books, search));
You need to be keeping the count, not the index at which it was found in result. You should increment the count only if the index is greater than or equal to zero. Note I’ve made a few optimizations as well to reduce the number of times you need to transform the strings. I’ve also added a different version that uses regular expressions.
Better alternative