0

I'm trying to find the number of total occurrences of a word in an array.
Here I found a solution and altered it a bit:

var dataset = ["word", "a word", "another word"];
var search = "word";
var count = dataset.reduce(function(n, val) {
  return n + (val === search);
}, 0);

Here is the fiddle.

But, instead of 3 I only get 1. So it only finds the first element, which is just word. But how to find all elements, containing word?

Community
  • 1
  • 1
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 2
    `return n + (val.indexOf(search) >= 0);` – Emissary Apr 13 '16 at 20:10
  • Can you please answer whether you want this to count ["word times three word word", "word"]` as four occurrences, or just 2? If it should be four, this actually becomes a bit more complex than most of the answers that have been given. – Katana314 Apr 13 '16 at 20:16
  • @Katana314: In my case there won't be multiple occurrences of a word within an element of an array. – Evgenij Reznik Apr 13 '16 at 20:19
  • My apologies, then, to the answerer that I downvoted. (Pretty much every answer had that issue, at which point I decided to clarify) – Katana314 Apr 13 '16 at 20:28

5 Answers5

1

Try this:

var dataset = ["word", "a word", "another word"];
var search = "word";
count = 0;

jQuery(dataset).each(function(i, v){ if(v.indexOf(search) != -1) {count ++} });

Here, count will be 3.

Abhi
  • 4,123
  • 6
  • 45
  • 77
0

You have to use String.prototype.indexOf() that return the index of the first occurence of the substring in the string, or -1 if not found:

var dataset = ["word", "a word", "another word"];
var search = "word";
var count = dataset.reduce(function(n, val) {
  return n + (val.indexOf(search) > -1 ? 1 : 0);
}, 0);
cl3m
  • 2,791
  • 19
  • 21
0

The operator === means: equal object and equal type.

If you are looking for each array element containing the 'search' word you need to use a different operator.

So, another possible approach, using filter and indexOf, is:

var dataset = ["word", "a word", "another word"];
var search = "word";
var count = dataset.filter(function(val) {
  return val.indexOf(search) != -1;
}).length;

document.write('N. words: ' + count)
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
0

You could use String#indexOf.

var dataset = ["word", "a word", "another word"],
    search = "word",
    count = dataset.reduce(function(r, a) {
        return r + !!~a.indexOf(search);
    }, 0);

document.write(count);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here is a one-line ES6 Arrow Function.

 const  countOccurrence = (arr,elem) =>  arr.filter((v) => v===elem).length;

Testing

const  countOccurrence = (arr,elem) =>  arr.filter((v) => v===elem).length;

//Testing
console.log(countOccurrence([1,2,3,4,5,6,1,8,9,1,1],1));
console.log(countOccurrence(['w','o','w'],'w'));
console.log(countOccurrence(['hello','world','hello'],'hello'));
Pranav HS
  • 53
  • 7