Home > other >  Why is my nested loop only finding one duplicate character in a string?
Why is my nested loop only finding one duplicate character in a string?

Time:12-04

My apologies if this is a duplicate, I couldn't find an answer after searching for a while on Stackoverflow. I am trying to use a nested loop to find any duplicate characters in a string. So far, all I can manage to do is to find one duplicate the string.

For example, when I try the string "aabbcde", the function returns ['a', 'a'], whereas I was expecting ['a', 'a', 'b', 'b'].

I obviously have an error in my code, can anybody help point me towards what it could be?

const myStr = "aabbcde";

function duplicateCount(text){
  const duplicates = [];
  for (let i = 0; i < text.length; i  ) {
    for (let j = 0; j < text[i].length; j  ) {
      if (text[i] === text[j]) {
        duplicates.push(text[i]);
      }
    }
  }
  return duplicates;
}

duplicateCount(myStr);

CodePudding user response:

Using nested loop will make it very hard to do it,we can use a Object to store the appear count,and then filter the count

const myStr1 = "aabbcde";
const myStr2 = "ffeddbaa";

const duplicateCount = str => {
  let map = {}
  for(c of str){
   map[c] = (map[c]??0)   1 
   }
   let result = []
   for(m in map){
    if(map[m] <= 1){
     continue 
    }
    result.push(...Array(map[m]).fill(m))
   }
   return result
}

console.log(duplicateCount(myStr1))
console.log(duplicateCount(myStr2))

CodePudding user response:

It should be something like this. issues in this loop for (let j = 0; j < text[i].length; j )

const myStr = "aabbcde";

function duplicateCount(text){
   const duplicates = [];
  for (let i = 0; i < text.length; i  ) {
    for (let j = i 1; j < text.length; j  ) {

      if (text[i] === text[j]) {
        duplicates.push(text[i]);
      }
    }
  }
  return duplicates;

}

console.log(duplicateCount(myStr));

CodePudding user response:

You can simply achieve the result you're looking for by creating an object map of the string (meaning each key of the object will be each unique character of the string and their associated values will be the number of times each character is repeated in the string).

After you create an object map of the string, you can loop through the object and check if each value is greater than one or not. If they're you would push that item into a result array by the number of times the character is repeated. Please find my code here:

const myStr = 'aabbcde';

const duplicateCount = (str) => {
  const result = [];
  const obj = {};
  str.split('').map((char) => {
    obj[char] = obj[char]   1 || 1;
  });
  for (key in obj) {
    if (obj[key] > 1) {
      for (let i = 0; i < obj[key]; i  ) {
        result.push(key);
      }
    }
  }
  return result;
};

console.log(duplicateCount(myStr));

  • Related