Why my code is printing extra value

I had the following problem in a interview which I did not pass and I been trying to make it work for me and following is my solution but ATM, the number is one more than what is given as argument

function checkForMostRepeatedWord(string){
    let obj = {}
    if(!string){
        return
    }
    for(let i = 0; i <string.length; i++){
        obj[string[i]] = 1
        for(let x = 0; x < string.length; x++){
            if(string[i] == string[x]){
                obj[string[i]] += 1
            }
        }
    }
    console.log(Object.keys(obj));
    console.log(Object.values(obj));
        return Object.values(obj)
}
checkForMostRepeatedWord("hheeell");

The following is the output

[ 'h', 'e', 'l' ]
[ 3, 4, 3 ]

Why is it printing a extra number whereas h is only 2 times.

Bacause your counting is starting from 1 : obj[string[i]] = 1
start from 0 and you will see the correct counting.

But I think that is what I want i.e. I want to set every word to 1, then if the word is repeated I want to increment that.

you right. ignore my previous comment as I was thinking wrong.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.