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 fee
Solution 1:
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);
Solution 2:
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
Solution 3:
var numOfString = 0;
var feed= newArray()
var feed= ["testABC", "test", "testABC"]
for(var i=0;i<feed.length;i++){
if(feed[i] === "testABC")
numOfString++;
}
console.log(numOfString);
Solution 4:
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= newArray()
var feed= ["testABC", "test", "testABC"]
var count = 0// ensure that our array contains the key you want prior to scanning itif(feed.findIndex("testABC") >= 0) {
for (var i=0; i < feed.length; i++ ) {
if(feed[i] === "testABC") count++
}
}
alert(count)
Solution 5:
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);
Post a Comment for "Javascript: Search String In Array Then Count Occurrences"