Javascript 从字符串中删除重复字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13841217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:54:32  来源:igfitidea点击:

Remove duplicate characters from string

javascriptstringduplicates

提问by Zlatko Soleniq

I have to make a function in JavaScript that removes all duplicated letters in a string. So far I've been able to do this: If I have the word "anaconda" it shows me as a result "anaconda" when it should show "cod". Here is my code:

我必须在 JavaScript 中创建一个函数来删除字符串中的所有重复字母。到目前为止,我已经能够做到这一点:如果我有“anaconda”这个词,它会在它应该显示“cod”时向我显示“anaconda”。这是我的代码:

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

回答by masterspambot

We can also now clean things up using filter method:

我们现在还可以使用 filter 方法清理内容:

function removeDuplicateCharacters(string) {
  return string
    .split('')
    .filter(function(item, pos, self) {
      return self.indexOf(item) == pos;
    })
    .join('');
}
console.log(removeDuplicateCharacters('baraban'));

Working example:

工作示例

回答by Cerbrus

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

console.log(find_unique_characters('baraban'));
console.log(find_unique_characters('anaconda'));

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. but obviously you know that already, otherwise there wouldn't be a question ;-)

您的代码至少返回字符串中的所有字符一次,而不是只返回出现不超过一次的字符。但显然你已经知道了,否则就不会有问题了;-)

回答by Aaron

Just wanted to add my solution for fun:

只是想添加我的解决方案以获得乐趣:

function removeDoubles(string) {
  var mapping = {};
  var newString = '';

  for (var i = 0; i < string.length; i++) {
    if (!(string[i] in mapping)) {
      newString += string[i];
      mapping[string[i]] = true;
    }
  }
  return newString;
}

回答by Lukasz Wiktor

With lodash:

使用lodash

_.uniq('baraban').join(''); // returns 'barn'

回答by suryadev

  //One simple way to remove redundecy of Char in String
       var char = "aaavsvvssff"; //Input string
       var rst=char.charAt(0);
       for(var i=1;i<char.length;i++){              
           var isExist = rst.search(char.charAt(i));
            isExist >=0 ?0:(rst +=  char.charAt(i) ); 
       }
       console.log(JSON.stringify(rst)); //output string : avsf

回答by Hien Nguyen

You can put character as parameter which want to remove as unique like this

您可以将字符作为要删除的唯一参数,如下所示

function find_unique_characters(str, char){
  return [...new Set(str.split(char))].join(char);
}

function find_unique_characters(str, char){
  return [...new Set(str.split(char))].join(char);
}

let result = find_unique_characters("aaaha ok yet?", "a");
console.log(result);

回答by David

For strings (in one line)

对于字符串(在一行中)

removeDuplicatesStr = str => [...new Set(str)].join('');

removeDuplicatesStr = str => [...new Set(str)].join('');

For arrays (in one line)

对于数组(在一行中)

removeDuplicatesArr = arr => [...new Set(arr)]

removeDuplicatesArr = arr => [...new Set(arr)]

回答by mplungjan

DEMO

演示

function find_unique_characters( string ){
    unique=[];
    while(string.length>0){
        var char = string.charAt(0);
        var re = new RegExp(char,"g");
        if (string.match(re).length===1) unique.push(char);
        string=string.replace(re,"");
    }        
    return unique.join("");
}
console.log(find_unique_characters('baraban')); // rn
console.log(find_unique_characters('anaconda')); //cod
?

回答by FBN10040

This code worked for me on removing duplicate(repeated) characters from a string (even if its words separated by space)

此代码适用于从字符串中删除重复(重复)字符(即使其单词由空格分隔)

Link: Working Sample JSFiddle

链接:工作示例 JSFiddle

/* This assumes you have trim the string and checked if it empty */
function RemoveDuplicateChars(str) {
   var curr_index = 0;
   var curr_char;
   var strSplit;
   var found_first;
   while (curr_char != '') {
      curr_char = str.charAt(curr_index);
      /* Ignore spaces */
      if (curr_char == ' ') {
         curr_index++;
         continue;
      }
      strSplit = str.split('');
      found_first = false;
      for (var i=0;i<strSplit.length;i++) {
         if(str.charAt(i) == curr_char && !found_first) 
            found_first = true;
         else if (str.charAt(i) == curr_char && found_first) {
            /* Remove it from the string */
            str = setCharAt(str,i,'');
         }
      }
      curr_index++;
   }
   return str;
}
function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

回答by asetniop

Here's what I used - haven't tested it for spaces or special characters, but should work fine for pure strings:

这是我使用的 - 尚未针对空格或特殊字符对其进行测试,但对于纯字符串应该可以正常工作:

function uniquereduce(instring){ 
    outstring = ''
    instringarray = instring.split('')
    used = {}
    for (var i = 0; i < instringarray.length; i++) {
        if(!used[instringarray[i]]){
            used[instringarray[i]] = true
            outstring += instringarray[i]
        }
    }
    return outstring
}