How to count the frequency of the digits (0 to 9) in a string with Node.js

1 Answer

0 votes
function countDigits(s) {
    const size = s.length;
    
    if (size == 0) {
        console.log("String is empry");
        return;
    }
    
    let digit_frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    
    for (let i = 0; i < size; i++) {
        if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
            digit_frequency[s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0)]++;
        }
    }
    
    for (let j = 0; j < 10; j++) {
        console.log(j + ": " + digit_frequency[j] + " times");
    }
}

const s = "c23c++4523node.js923988rust82215";

countDigits(s);





/*
run:

0: 0 times
1: 1 times
2: 5 times
3: 3 times
4: 1 times
5: 2 times
6: 0 times
7: 0 times
8: 3 times
9: 2 times

*/

 



answered Jun 2, 2023 by avibootz
...