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++);
    }
} 
5
  • 2
    please add some data for feed. Jun 7, 2016 at 18:34
  • 1
    what about feed = ["testABC testABC"] - two occurences?
    – le_m
    Jun 7, 2016 at 19:12
  • And is ["testABCtestABC"] one, two, or none?
    – 1983
    Jun 7, 2016 at 19:30
  • You might want to take a look at the Array iteration methods. These are nearly always more appropriate than a for-loop.
    – 1983
    Jun 7, 2016 at 19:52
  • Possible duplicate of Count instances of string in an array
    – 1983
    Jun 7, 2016 at 20:35

10 Answers 10

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

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
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);
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)
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);
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
3
  • @OlegMikhailov, I don't think so. That is not too complicated case to talk about readability. Too simple Jun 7, 2016 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. Jun 7, 2016 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 Jun 7, 2016 at 19:50
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.

1
  • You've written var feed = twice. But even corrected it does not work. Jun 7, 2016 at 19:54
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.

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)

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.