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
  • 20,339
  • 15
  • 51
  • 79
David Garcia
  • 2,688
  • 18
  • 52
  • 86
  • 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
  • 351,820
  • 24
  • 303
  • 358
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
  • 959
  • 7
  • 16
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,479
  • 9
  • 13
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,774
  • 3
  • 22
  • 42
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
  • 694
  • 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
  • 744
  • 1
  • 6
  • 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
  • 75,918
  • 4
  • 51
  • 91
  • @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
  • 17,771
  • 9
  • 60
  • 73
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 Arguelles
  • 17,270
  • 4
  • 37
  • 42
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
  • 72
  • 1
  • 8