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. Commented Jun 7, 2016 at 18:34
  • 1
    what about feed = ["testABC testABC"] - two occurences? Commented Jun 7, 2016 at 19:12
  • And is ["testABCtestABC"] one, two, or none? Commented 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. Commented Jun 7, 2016 at 19:52
  • Possible duplicate of Count instances of string in an array Commented 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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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)

Comments

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

Comments

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 Comments

@OlegMikhailov, I don't think so. That is not too complicated case to talk about readability. Too simple
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.
@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
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 Comment

You've written var feed = twice. But even corrected it does not work.
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.

Comments

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)

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.