David Garcia
David Garcia

Reputation: 2696

Javascript: search string in array then count occurrences

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

Upvotes: 3

Views: 1273

Answers (10)

codecumber
codecumber

Reputation: 112

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)

Upvotes: 0

Yosvel Quintero
Yosvel Quintero

Reputation: 19090

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)

Upvotes: 0

Nika
Nika

Reputation: 1964

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.

Upvotes: 2

le_m
le_m

Reputation: 20248

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.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

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

Upvotes: 2

Sergey Khalitov
Sergey Khalitov

Reputation: 1037

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

Upvotes: 4

Jumpa
Jumpa

Reputation: 918

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

Upvotes: 2

Eissa
Eissa

Reputation: 700

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)

Upvotes: 2

Tanvi B
Tanvi B

Reputation: 1567

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

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386868

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

Upvotes: 5

Related Questions