0

How do you count patterns in record fields and create an array of it?

For example:

Searching in (using my example below) currently gives me multiple outputs of

0 0 (**in** seen at index 0 of book 0 title record)

0 13 (**in** seen at index 13 of book 0 title record)

1 19 (**in** seen at index 0 of book 1 title record)

2 -1 (**in** not seen at any index of title record)

Ideally I would like the code to return:

2,1,0 (**in** seen 2 times in book 0 title record, **in** seen 1 time in 
book 1 title record and **in** not seen in book 2 title record

Thanks in advance!

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) {
    if (pattern) {
        var num = 0;
        var result = [];
        for (i = 0; i < books.length; i++) {
            var index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase());
            do {
                alert(i + " " + index);
                index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1);
            }
            while (index >= 0)
            num = 0;
        }
        return result;
    }
    else {
        return ("Nothing entered!");
    }
}
alert(count(books, search));
methuselah
  • 12,766
  • 47
  • 165
  • 315

1 Answers1

1

Use String.prototype.match, it returns an array of the matches (or null if there were none), the length of the array tells you how many matches there were. e.g.

var 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",
    }
];
var result = [];
var re = /in/ig; 
var matches;
for (var i=0, iLen=books.length; i<iLen; i++) {
  matches = books[i].title.match(re);
  result.push(matches? matches.length : 0);
}
alert(result);
RobG
  • 142,382
  • 31
  • 172
  • 209