Javascript: Search String in Array Then Count Occurrences

Javascript: search string in array then count occurrences

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

How to count string occurrence in array of strings?

Try following

var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
console.log(arr.filter((item) => item.startsWith('male')).length);

How to count string occurrence in string?

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

var temp = "This is a string.";var count = (temp.match(/is/g) || []).length;console.log(count);

How to count occurrences of strings in array of arrays?

Use flat() and reduce():

const data = [
["Blue", "Green"],
["Red", "Black", "White", "Other"],
["Green", "Gold"],

const result = data.flat().reduce((a, v) => (a[v] = (a[v] || 0) + 1, a), {});


Count instances of string in an array

Using a basic, old-fashioned loop:

var numOfTrue = 0;
for(var i=0;i<Answers.length;i++){
if(Answers[i] === "true")

or, a reduce

var numOfTrue = Answers.reduce((acc,curr) => {
if(curr === "true")
return acc;

or a filter

var numOfTrue = Answers.filter(x => x === "true").length;

Count string occurrences in an array

You could for example use a Map to count the number of occurrences. Use the first item from split as the key and start with 1.

For every same key, increment the value by 1.

Assuming all the values have a an underscore present:

const folders = ["a_x_y_1", "b_x_y_1", "b_x_y_3", "b_x_y_2", "c_x_y_1", "c_x_y_2", "d_x_y_1"];
const m = new Map();

const result = folders.forEach(folder => {
const part = folder.slice(0, folder.lastIndexOf('_'));
!m.has(part) ? m.set(part, 1) : m.set(part, m.get(part) + 1);

for (const [key, value] of m.entries()) {

count occurrences of multiple search

Thankyou for your answers,
I've been trying since i post this, and I came with:

function map_it(data_items, dim_key) {
var bucket = {};
categoryList.forEach(function (cat) {
bucket[cat] = 0;
data_items.forEach(function (item) {
if (Object.keys(bucket).indexOf(item.category) >= 0) bucket[item.category]++;
else bucket[item.category] = 1;
return bucket;

Javascript count occurrences of Array in String

In fact, you don't need any loops at all. Just construct one big regexp with alternatives (|) and match the string against it:

var tce = [":)", ":(", ":/"];

RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')

var re = RegExp('|'), "g");

var msg = "hello :/ world :):)";
var countOcurrences = (msg.match(re) || "").length; // 3

Related Topics

Leave a reply