skip to Main Content

I have a homework assignment where I have to extract duplicate characters from a string and place them in another string.
exp:

const str = "love to learn javascript"

the new string would be

const str2 = "love tarnjscip"

I didn’t made any try as I’m a beginner and I don’t have an initial idea how to start (I think the solution is a nested loop)

Can you help me and give me different ways to handle this kind of exercise?

4

Answers


  1. here i created an empty array and i pushed to it every unique letter, then in the next round i check if a letter already added so it means the letter repeated then i call continue to skip to the next round if the letter repeated or i add the letter if it is not.
    hope this works for you.

    const sentence = "love to learn javascript"
    
    const letters = []
    let result = ''
    for(const item of sentence)
    {
      const check = letters.find((i)=>i===item)
      if(check)continue;
      letters.push(item)
      result += item
    }
    console.log(result)
    Login or Signup to reply.
  2. You can use an object to easily keep track of which letters you already encountered.

    const str = "love to learn javascript"
    
    let str2 = "";
    
    let letters = {};
    
    for(let i=0, l=str.length; i<l; ++i) {
      let letter = str[i];
      if(!letters[letter]) { // if the object does not have a property
                             // named after the current letter yet
        str2 += letter; // then add that letter to the result string
      }
      letters[letter] = 1; // set the object property for the current letter
    }
    
    console.log(str2)
    Login or Signup to reply.
  3. This code iterates through each character in the str string. It checks if the current character is a duplicate by comparing the last occurrence index with the first occurrence index of that character. If they are not equal, it means the character appears more than once.

    const str = "love to learn javascript";
    let str2 = "";
    
    for (let i = 0; i < str.length; i++) {
      if (str.lastIndexOf(str[i]) !== str.indexOf(str[i])) {
        if (!str2.includes(str[i])) {
          str2 += str[i];
        }
      }
    }
    

    Demo

    const str = "love to learn javascript";
    let str2 = "";
    
    for (let i = 0; i < str.length; i++) {
      if (str.lastIndexOf(str[i]) !== str.indexOf(str[i])) {
        if (!str2.includes(str[i])) {
          str2 += str[i];
        }
      }
    }
    
    console.log(str2);
    Login or Signup to reply.
  4. You could use Set:

    const r = [...new Set("love to learn javascript").values()].join('');
    console.log(r);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search