Search code examples
javascriptstringunique

Javascript: Determine if all characters in a string are unique and if not, delete duplicate characters


Have an array set up with a[letter][occurences], but struggling with looping through this array, to check for occurences > 1 and removing the ones that are.

function charFreq(s) {
    var i, j;
    var a = new Array();

    for (j = 0; j < s.length; j++) {
        for (i = 0; i < a.length; i++) {
            if (a[i][0] == s[j]) {
                a[i][1]++;
                break;
            }
        }
        if (i == a.length) {
            a[i] = [s[j], 1];
        }
    }
    return a[i][0];
}
document.write(charFreq("insert string here"));

This is the mess I've come up with so far:

function check(str) {
    var c;
    for (c=0; c < a.length; c++) {
        if(a[c][1] == 1) {
            return true;
            break;
        } else {
            return false;
        }
    }
}

Solution

  • Don't do it that way.

    function noDups( s ) {
      var chars = {}, rv = '';
    
      for (var i = 0; i < s.length; ++i) {
        if (!(s[i] in chars)) {
          chars[s[i]] = 1;
          rv += s[i];
        }
      }
    
      return rv;
    }
    
    alert(noDups("Shoe fly pie, and apple pan dowdy")); // Shoe flypi,andw
    

    As the length of your string gets longer, your code gets slower by a factor roughly equal to the square of the length of the string.