JSNewb
JSNewb

Reputation: 65

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;
        }
    }
}

Upvotes: 4

Views: 7582

Answers (7)

Alan R. Soares
Alan R. Soares

Reputation: 1804

Using ES6 Set:

// :: unique = Array<any>|string => Array<any>
const unique = xs => [...new Set(xs)]

const dedupe = str => unique(str).join('')

console.log(
  unique('foo'), // => ['f', 'o']
  dedupe('foo'), // => 'fo'
)

Upvotes: 3

kennebec
kennebec

Reputation: 104840

This assumes only alpha characters, and upper case not equal to lower case.

function uniqueChars(string){
    var i= 0, L= string.length, ustring= '', next;
    while(i<L){
        next= string.charAt(i++);
        if(ustring.indexOf(next)== -1) ustring+= next;
    }
    return ustring.replace(/[^a-zA-Z]/g, '');
}
var s1= 'The quick red fox jumps over the lazy brown dog.';
uniqueChars(s1)

/* returned value: (String) Thequickrdfoxjmpsvtlazybwng */

This returns any unique character-

function uniqueArray(array){
    return array.filter(function(itm, i, T){
        return T.indexOf(itm)== i;
    });
}
var s1= 'The quick red fox jumps over the lazy brown dog.';
uniqueArray(s1.split('')).join('');

/* returned value: (String) The quickrdfoxjmpsvtlazybwng. */

Upvotes: 0

RobG
RobG

Reputation: 147513

I can't see a splice version, so here's one:

function uniqueChars(s) {
  var s = s.split('');
  var c, chars = {}, i = 0;

  while ((c = s[i])) {
    c in chars? s.splice(i, 1) : chars[c] = ++i;
  }
  return s.join('');
}

Upvotes: 0

Rob Hardy
Rob Hardy

Reputation: 1821

function RemoveDuplicateLetters(input) {
    var result = '', i = 0, char = '';
    while (i < input.length) {
        char = input.substring(i, i+1);
        result += char;
        input = input.replace(char,'');
    }
    return result;
}

Upvotes: 0

elclanrs
elclanrs

Reputation: 94131

Here's a quick way:

str = str.split('').filter(function(v,i,self){
  return self.indexOf(v) == i;
}).join('');

Upvotes: 0

luisurrutia
luisurrutia

Reputation: 586

To delete duplicate characters from an string, you can use the next function that made the user @Cerbrus

function find_unique_characters( string ){
    var unique='';
    for(var i=0; i<string.length; i++){
        if(string.lastIndexOf(string[i]) == string.indexOf(string[i])){
            unique += string[i];
        }
    }
    return unique;
}
console.log(find_unique_characters('baraban'));

If you only want to return characters that appear occur once in a string, check if their last occurrence is at the same position as their first occurrence.

Your code was returning all characters in the string at least once, instead of only returning characters that occur no more than once

Link to the thread of stackoverflow Remove duplicate characters from string

Upvotes: 0

Pointy
Pointy

Reputation: 413996

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.

Upvotes: 1

Related Questions