Search code examples
javascriptunicode

How do I sort characters of a string by appearance order?


I have the following code:

function main() {
  let input = prompt("Enter a string:").toLowerCase().replace(/\s/g, "");
  let process = "";

  for (let i = 0; i < input.length; i++) {
    let word = input[i];
    let repeatWord = "";
    for (let j = 0; j < word.length; j++) {
      repeatWord += word[j].repeat(j + 1);
    }
    process += repeatWord;
  }
  console.log(process);
}

How do I sort the characters of the string by order of first appearance?

For example, if I enter the string: "Learning Center", then the expected result should be "leeearrnnigct".


Solution

  • Here is yet another version. This one will keep blanks and distinguish between upper/lower case letters:

    const str="Learning Center".split(""),
      freq={};
    str.forEach(c=>freq[c]=(freq[c]??0)+1);
    const res=str.map(c=>{
     let s=c.repeat(freq[c]);
     freq[c]=0;
     return s
    }).join("");
    
    console.log(res);

    If you prefer a case insensitive solution without blanks then simply modify it to:

    const str="Learning Center".toLowerCase().replaceAll(" ","").split(""),
      freq={};
    str.forEach(c=>freq[c]=(freq[c]??0)+1);
    const res=str.map(c=>{
     let s=c.repeat(freq[c]);
     freq[c]=0;
     return s
    }).join("");
    
    console.log(res);