3

I am using indexOf to search for a string in an array, how can I continue to count the number of occurences? I tried the latter but it isn't working.

var feed= new Array();
var feed= ["testABC", "test", "testABC"];

if (feed.indexOf("testABC") != -1) {
    for (var i=0; i < feed.indexOf("testABC").length; i++ ) {
        logInfo("found"+feed++);
    }
} 
Mohammad
  • 21,175
  • 15
  • 55
  • 84
David Garcia
  • 3,056
  • 18
  • 55
  • 90
  • 2
    please add some data for `feed`. – Nina Scholz Jun 07 '16 at 18:34
  • 1
    what about `feed = ["testABC testABC"]` - two occurences? – le_m Jun 07 '16 at 19:12
  • And is `["testABCtestABC"]` one, two, or none? – 1983 Jun 07 '16 at 19:30
  • You might want to take a look at the [Array iteration methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods). These are nearly always more appropriate than a for-loop. – 1983 Jun 07 '16 at 19:52
  • Possible duplicate of [Count instances of string in an array](http://stackoverflow.com/questions/9996727/count-instances-of-string-in-an-array) – 1983 Jun 07 '16 at 20:35

10 Answers10

5

You can set a count variable and iterate over the elements of feed. Then check if the element has indexOf unequal -1 (means found) and count the occurence.

var feed = ["testABC", "test", "testABC"],
    count = 0,
    i;

for (i = 0; i < feed.length; i++) {
    if (feed[i].indexOf("testABC") !== -1) {
        count++;
    }
}

console.log(count);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
4

Try to use Array.prototype.forEach function:

var feed  = ['foo','testABC','bar','testABC','testABC'];
var count = 0;
feed.forEach(function(value){
    if(value=='testABC') count++;
});
console.log(count); //3

Or Array.prototype.filter function:

var feed  = ['foo','testABC','bar','testABC','testABC'];
var count = feed.filter( function(value) { return value=='testABC' } ).length;
console.log(count); //3
Sergey Khalitov
  • 987
  • 7
  • 17
2
var numOfString = 0;
var feed= new Array()
var feed= ["testABC", "test", "testABC"]

for(var i=0;i<feed.length;i++){
    if(feed[i] === "testABC")
       numOfString++;
}
console.log(numOfString);
Tanvi B
  • 1,577
  • 11
  • 14
2

try:

var feed = ["testABC", "test", "testABC"],
count = feed.filter(function(v) { return v.indexOf('test') > -1; }).length;

EDIT: removed duplicate feed = feed. also, I had startsWith instead of indexOf. It should work now.

Nika
  • 1,864
  • 3
  • 23
  • 44
2

Here's a simple and straight forward solution. You may want to make it a function in the case that you want to reuse your code.

var feed= new Array()
var feed= ["testABC", "test", "testABC"]
var count = 0

// ensure that our array contains the key you want prior to scanning it
if(feed.findIndex("testABC") >= 0) {
    for (var i=0; i < feed.length; i++ ) { 
    if(feed[i] === "testABC") count++
  }
}

alert(count)
Eissa
  • 700
  • 5
  • 17
2

In addition to all the ways the other stated, if you are using ES6 you can use the 'for of' loop to iterate all the array's values:

var numOfString = 0;
var feed = ["testABC", "test", "testABC"];
for(let currentString of feed) {
  if(currentString.indexOf('testABC') !== -1) {
    numOfString += 1;
  }
}
console.log(numOfString);
Jumpa
  • 878
  • 1
  • 8
  • 12
2

It can be achieved with one line of code using ES6 arrow function expression:

var feed = ["testABC", "test", "testABC"], count = 0;

feed.forEach((v) => v === "testABC" && count++);

console.log(count);  // 2
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • @OlegMikhailov, I don't think so. That is not too complicated case to talk about readability. Too simple – RomanPerekhrest Jun 07 '16 at 19:29
  • Yeah, but who knows what this function becomes in future... It is always a good time to talk about readability). Programs are written for humans then. – Oleg Mikhailov Jun 07 '16 at 19:38
  • @OlegMikhailov, " but who knows" - nobody knows. When someone will ask for the extended and complex case - I'll write new solution. But for now, "one-line" solution will be also good – RomanPerekhrest Jun 07 '16 at 19:50
1

If feed = ["testABC testABC"] counts as two occurences of "testABC", then I suggest the following code:

var feed = ["testABC", "test", "testABC"];

var count = (feed.join('').match(/testABC/g) || []).length;

console.log(count)

See also How to count string occurrence in string?

Arbitrary search strings would need escaping for special regex characters.

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
0

You can also use regular expressions and the String.prototype.match()

Code:

const feed = ["testABC", "test", "testABC"];
const count = feed.toString().match(/testABC/g).length;

console.log(count)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

Or you can simply use reduce() method:

    const feed = ["testABC", "test", "testABC", 'testABC'];

    const count = feed.reduce((acc, val) => (acc[val] = acc[val] + 1 || 1, acc), {})['testABC']

    console.log(count)
codecumber
  • 102
  • 3
  • 9