Search code examples
javascriptstringloopscounter

How to access previous values inside a loop?


I'm kinda new to JS programming and I'm sorry if this is an obvious question. I have a code that counts the repeated letters in a string. The code should only output the letters that are used more than twice.

For example:

let str = "HELLOWORLD"

Output should be : L = 3, O = 3

My code outputs: L =3, O = 2, O =2, L = 3

I wanted to get rid of the second O and L.

function repeat(){
    let str = "helloworld";
    let letters = "";
    let count = "";
    let output = "";
    let x = "";
    for (i = 0; i <str.length; i++){
    letters = str.charAt(i); 
    count = str.split(letters).length - 1;
    if (count >= 2 && x !== letters) {
    output += letters +"=" + count + " ";
    }
    x = letters;
}
console.log(output);
}

repeat();

I can only remove a duplicate letter if it comes before the new one because of the x = letters; code. I would like the characters to appear only once, but I'm having a hard time with the loops. I know it looks messy and needs improvement, but i'll work on it after I figure out my solution. Any advice would be appreciated!


Solution

  • You can keep repeated letters in an array and then check if the letter already exists.

    function repeat(){
        let str = "helloworld";
        let letters = "";
        let count = "";
        let output = "";
        let x = "";
        let multipleChars = [];
        for (i = 0; i <str.length; i++){
        letters = str.charAt(i);
        count = str.split(letters).length - 1;
        if (count >= 2 && x !== letters && !multipleChars.includes(letters)) {
        output += letters +"=" + count + " ";
        multipleChars.push(letters);
        }
        x = letters;
    }
    console.log(output);
    }
    
    repeat();