简体   繁体   中英

Find all occurrences of word in array

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 ?

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.

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);

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) 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM