methuselah
methuselah

Reputation: 13206

Counting results in an JavaScript array

How do you count results within an array?

I am counting the occurrences of a pattern in an array and could like it to return as

[0, 0, 0]

For example with each element of the array representing a search result.

This is what I've done so far... but it seems to only return [object object]...

pages=[
"Lorem Ipsum is simply dummy text of the printing and typesetting industry."
, 
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout", 
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable." 
]
pattern = prompt("Enter a search string")

    var count = {};

    for(i=0; i<pages.length; i++)
    {
         for(j=0; j<pattern.length; j++)
         {
               if((pages[i].toLowerCase()
                           .indexOf(pattern.toLowerCase()
                                           .charAt([j])))<0)
               {
                  count[i]++;
               }
         }
    }

    alert(count);

Upvotes: 0

Views: 116

Answers (2)

James
James

Reputation: 22227

var count, allCounts = [];

for(i=0; i<pages.length; i++)
{
     count = 0;
     for(j=0; j<pattern.length; j++)
     {
           if((pages[i].toLowerCase()
                       .indexOf(pattern.toLowerCase()
                                       .charAt([j])))<0)
           {
              count++;
           }
     }
     allCounts.push(count);
}
alert('[' + allCounts.join(', ') + ']');

I suggest that you .toLowerCase your pattern once before the start of any of the loops, that would avoid doing the toLowerCase operation i * j times.

Upvotes: 1

Amr Elgarhy
Amr Elgarhy

Reputation: 68902

I think you need to move the alert(count) up 2 lines to be like this:

var count = {};

           for(i=0;i<pages.length;i++)
           {
               for(j=0;j<pattern.length;j++)
                   {
                       if((pages[i].toLowerCase().indexOf(pattern.toLowerCase().charAt([j])))<0)
                       {
                           count[i]++;
                       }
                   }
            alert(count[i]); // but note that it will appear multiple times
           }

Upvotes: 1

Related Questions