Open In App

Least Frequent Character in String in JavaScript

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, finding the least frequent character in a string involves identifying the character that occurs the fewest times within the given string by iterating through the string, counting the occurrences of each character, and determining the one with the minimum frequency.

This algorithmic task is essential for analyzing and manipulating strings in JavaScript, contributing to various applications such as data processing, pattern recognition, and text analytics.

There are several ways in which this task can be performed using JavaScript which are as follows:

Using a Frequency Counter Object

Create a frequency counter object to count the occurrences of each character in the string to Iterate through the frequency counter object to find the character with the minimum frequency.

Example: JavaScript program utilizing an object frequency counter to find the least frequent character in a given string.

Javascript




function leastFrequentCharacter(str) {
    const freqCounter = {};
    for (const char of str) {
        freqCounter[char] = (freqCounter[char] || 0) + 1;
    }
    let minFrequency = Infinity;
    let leastFrequentChar = '';
    for (const char in freqCounter) {
        if (freqCounter[char] < minFrequency)
        {
            minFrequency = freqCounter[char];
            leastFrequentChar = char;
        }
    }
    return leastFrequentChar;
}
 
console.log(leastFrequentCharacter('geeksforgeeks'));


Output

f

Sorting the Character Frequencies Array

Create an array to store the frequencies of each character in the string. Sort the array in ascending order and then return the character corresponding to the minimum frequency in the sorted array.

Example: JavaScript program employing object and map structures to find the least frequent character in a string.

Javascript




function leastFrequentCharacter(str) {
    const charFreq = [];
    for (const char of str) {
        const index = charFreq.findIndex(item => {
            return item.char === char
        });
        if (index !== -1) {
            charFreq[index].count++;
        } else {
            charFreq.push({ char, count: 1 });
        }
    }
    charFreq.sort((a, b) => a.count - b.count);
    return charFreq[0].char;
}
 
console.log(leastFrequentCharacter('geeksforgeeks'));


Output

f


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads