How to display string letters sorted by frequency in JavaScript

1 Answer

0 votes
// sortByFrequency — counts how often each letter appears and returns a sorted list
function sortByFrequency(s) {
    // Create a frequency array for 26 lowercase letters, initialized to 0
    const freq = Array(26).fill(0);

    // Iterate through the string and count only alphabetic characters
    for (const c of s) {
        if (/[a-zA-Z]/.test(c)) {
            const idx = c.toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0);
            freq[idx]++;
        }
    }

    // Build an array of {letter, freq} pairs
    const result = [];
    for (let i = 0; i < 26; i++) {
        result.push({
            letter: String.fromCharCode('a'.charCodeAt(0) + i),
            freq: freq[i]
        });
    }

    // Sort pairs by frequency in descending order
    result.sort((a, b) => b.freq - a.freq);

    return result;
}

// Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
function buildSortedString(sorted) {
    let out = "";

    for (const p of sorted) {
        // append 'p.letter' repeated p.freq times
        if (p.freq > 0) {
            out += p.letter.repeat(p.freq);
        }
    }

    return out;
}

// Input text to analyze
const text = "bbcabddddccafffadbbcdccsedddddhhgade";

// Get sorted frequency list
const sorted = sortByFrequency(text);

// Print each letter and its frequency
for (const p of sorted) {
    if (p.freq !== 0) {
        console.log(`${p.letter}: ${p.freq}`);
    }
}

// Print the reconstructed sorted string
const lettersSortedByFrequency = buildSortedString(sorted);
console.log("\nSorted string:", lettersSortedByFrequency);



/*
run:

d: 12
c: 6
b: 5
a: 4
f: 3
e: 2
h: 2
g: 1
s: 1

Sorted string: ddddddddddddccccccbbbbbaaaafffeehhgs

*/

 



answered 2 days ago by avibootz
...