Find the Exact Individual Count of Array of String in Array of Sentences in JavaScript

In JavaScript, you often need to count how many times specific strings appear in an array of sentences. This article demonstrates how to find the exact individual count of each string from a given array within multiple sentences using regular expressions and word boundaries.

Understanding the Problem

Given an array of strings and an array of sentences, we need to count how many times each string appears across all sentences. The key requirement is to match complete words only, not partial matches within other words.

// Example input:
const strings = ["car", "cycle", "bike"];
const sentences = ["I have a car and a bike.", "The car is fast but the cycle is slow."];

// Expected output: { car: 2, cycle: 1, bike: 1 }

Algorithm

Our approach involves creating a count object, iterating through sentences, and using regular expressions with word boundaries to match exact words:

Step 1: Initialize a count object with each string set to 0

Step 2: Loop through each sentence in the sentences array

Step 3: For each sentence, check each string using regex with word boundaries

Step 4: Count matches and add to the total count for each string

Implementation

function countStrings(strings, sentences) {
    const counts = {};
    
    // Initialize counts for each string
    for (let i = 0; i < strings.length; i++) {
        counts[strings[i]] = 0;
    }
    
    // Iterate through each sentence
    for (let i = 0; i < sentences.length; i++) {
        const sentence = sentences[i];
        
        // Check each string in the current sentence
        for (let j = 0; j < strings.length; j++) {
            const string = strings[j];
            
            // Use word boundaries to match exact words
            const regex = new RegExp('\b' + string + '\b', 'gi');
            const matches = sentence.match(regex);
            const count = matches ? matches.length : 0;
            
            counts[string] += count;
        }
    }
    
    return counts;
}

// Test the function
const strings = ['apple', 'banana', 'orange'];
const sentences = [
    'I have an apple and a banana.',
    'She likes orange juice but I prefer banana smoothies.',
    'The apple pie contains apple slices.'
];

const result = countStrings(strings, sentences);
console.log(result);
{ apple: 3, banana: 2, orange: 1 }

Key Features

Word Boundaries: The regex \b ensures we match complete words only. For example, "car" won't match within "card" or "scar".

Case Insensitive: The 'gi' flags make the search global and case-insensitive, so "Apple" and "apple" are treated the same.

Alternative Approach Using Modern JavaScript

function countStringsModern(strings, sentences) {
    const counts = Object.fromEntries(strings.map(str => [str, 0]));
    
    sentences.forEach(sentence => {
        strings.forEach(string => {
            const regex = new RegExp(`\b${string}\b`, 'gi');
            const matches = sentence.match(regex);
            counts[string] += matches ? matches.length : 0;
        });
    });
    
    return counts;
}

// Test with the same data
const modernResult = countStringsModern(strings, sentences);
console.log(modernResult);
{ apple: 3, banana: 2, orange: 1 }

Performance Analysis

Aspect Complexity Description
Time Complexity O(s × n × m) s = sentences, n = strings, m = avg sentence length
Space Complexity O(n) Storage for the counts object

Conclusion

Using regular expressions with word boundaries provides an accurate way to count exact string matches in sentences. The approach efficiently handles case-insensitive matching while avoiding partial word matches, making it reliable for text analysis tasks.

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

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements