Find all occurrences of a word in array in JavaScript

When working with arrays in JavaScript, you might need to find how many elements contain a specific word or substring. This article demonstrates multiple approaches to count occurrences of a word within array elements.

Problem Statement

We need to write a JavaScript function that takes an array of strings as the first argument and a search word as the second argument. The function should return the count of array elements that contain the specified word.

Method 1: Using filter() and indexOf()

This approach uses filter() to find matching elements and returns the length of the filtered array.

const arr = ["word", "a word", "another word"];
const query = "word";

const findAll = (arr, query) => {
    let count = 0;
    count = arr.filter(el => {
        return el.indexOf(query) != -1;
    }).length;
    return count;
};

console.log(findAll(arr, query));
3

Method 2: Using includes() Method

A more modern and readable approach using the includes() method:

const arr = ["word", "a word", "another word", "test"];
const query = "word";

const findAllIncludes = (arr, query) => {
    return arr.filter(element => element.includes(query)).length;
};

console.log(findAllIncludes(arr, query));
3

Method 3: Using reduce() for Counting

Using reduce() provides more control over the counting process:

const arr = ["word", "a word", "another word", "testing"];
const query = "word";

const findAllReduce = (arr, query) => {
    return arr.reduce((count, element) => {
        return element.includes(query) ? count + 1 : count;
    }, 0);
};

console.log(findAllReduce(arr, query));
3

Case-Insensitive Search

To make the search case-insensitive, convert both the array elements and search query to lowercase:

const arr = ["Word", "A WORD", "another word", "testing"];
const query = "word";

const findAllCaseInsensitive = (arr, query) => {
    return arr.filter(element => 
        element.toLowerCase().includes(query.toLowerCase())
    ).length;
};

console.log(findAllCaseInsensitive(arr, query));
3

Comparison of Methods

Method Readability Performance Flexibility
filter() + indexOf() Good Good Moderate
filter() + includes() Excellent Good Good
reduce() Good Excellent Excellent

Conclusion

The includes() method with filter() provides the most readable solution for finding word occurrences in arrays. Use reduce() when you need more control over the counting logic.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements