Javascript 只显示一次字符串中的唯一字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13868043/
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:59:39  来源:igfitidea点击:

Showing unique characters in a string only once

javascriptstringcharacterunique

提问by Zlatko Soleniq

I have a string with repeated letters. I want letters that are repeated more than once to show only once. For instance I have a string aaabbbccc i want the result to be abc. so far my function works like this:

我有一个带有重复字母的字符串。我希望重复多次的字母只显示一次。例如我有一个字符串 aaabbbccc 我希望结果是 abc。到目前为止,我的功能是这样工作的:

  • if the letter doesn't repeat, it's not shown
  • if it's repeated once, it's show only once (i.e. aa shows a)
  • if it's repeated twice, shows all (i.e. aaa shows aaa)
  • if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa)
  • 如果字母不重复,则不会显示
  • 如果重复一次,则只显示一次(即 aa 显示 a)
  • 如果重复两次,则显示全部(即 aaa 显示 aaa)
  • 如果重复 3 次,则显示 6(如果 aaaa,则显示 aaaaaa)
function unique_char(string) {
    var unique = '';
    var count = 0;
    for (var i = 0; i < string.length; i++) {
        for (var j = i+1; j < string.length; j++) {
            if (string[i] == string[j]) {
                count++;
                unique += string[i];
            }
        }
    }
    return unique;
}

document.write(unique_char('aaabbbccc'));

The function must be with loop inside a loop; that's why the second foris inside the first.

函数必须在循环内循环;这就是为什么第二个for在第一个里面。

回答by Upayavira

Convert it to an array first, then use the answer here, and rejoin, like so:

首先将其转换为数组,然后使用此处的答案,然后重新加入,如下所示:

var nonUnique = "ababdefegg";
var unique = nonUnique.split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');

All in one line :-)

全部在一行中 :-)

回答by le_m

Fill a Setwith the characters and concatenate its unique entries:

Set用字符填充 a并连接其唯一条目:

function makeUnique(str) {
  return String.prototype.concat(...new Set(str))
}

console.log(makeUnique('abc'));    // "abc"
console.log(makeUnique('abcabc')); // "abc"

回答by Parthasarathy K

Too late may be but still my version of answer to this post:

可能为时已晚,但仍然是我对这篇文章的回答:

function extractUniqCharacters(str){
    var temp = {};
    for(var oindex=0;oindex<str.length;oindex++){
        temp[str.charAt(oindex)] = 0; //Assign any value
    }
    return Object.keys(temp).join("");
}

回答by Bergi

You can use a regular expressionwith a custom replacement function:

您可以使用带有自定义替换函数正则表达式

function unique_char(string) {
    return string.replace(/(.)*/g, function(sequence, char) {
         if (sequence.length == 1) // if the letter doesn't repeat
             return ""; // its not shown
         if (sequence.length == 2) // if its repeated once
             return char; // its show only once (if aa shows a)
         if (sequence.length == 3) // if its repeated twice
             return sequence; // shows all(if aaa shows aaa)
         if (sequence.length == 4) // if its repeated 3 times
             return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
         // else ???
         return sequence;
    });
}

回答by brian buck

Per the actual question: "if the letter doesn't repeat its not shown"

根据实际问题:“如果字母不重复,则未显示”

function unique_char(str)
{
    var obj = new Object();

    for (var i = 0; i < str.length; i++)
    {
        var chr = str[i];
        if (chr in obj)
        {
            obj[chr] += 1;
        }
        else
        {
            obj[chr] = 1;
        }
    }

    var multiples = [];
    for (key in obj)
    {
        // Remove this test if you just want unique chars
        // But still keep the multiples.push(key)
        if (obj[key] > 1)
        {
            multiples.push(key);
        }
    }

    return multiples.join("");
}

var str = "aaabbbccc";
document.write(unique_char(str));

回答by cottonke

Your problem is that you are adding to uniqueevery time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):

您的问题是unique每次在string. 真的你应该做这样的事情(因为你指定答案必须是嵌套的 for 循环):

function unique_char(string){

    var str_length=string.length;
    var unique='';

    for(var i=0; i<str_length; i++){

        var foundIt = false;
        for(var j=0; j<unique.length; j++){

            if(string[i]==unique[j]){

                foundIt = true;
                break;
            }

        }

        if(!foundIt){
            unique+=string[i];
        }

    }

   return unique;
}

document.write( unique_char('aaabbbccc'))

In this we only add the character found in stringto uniqueif it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.

在这里,我们只添加在其中找到的字符stringunique如果它不存在。这实际上根本不是一种有效的方法……但是根据您的要求,它应该可以工作。

I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.

我无法运行它,因为我没有任何方便的东西可以在其中运行 JavaScript ……但是这种方法中的理论应该可行。

回答by Lukasz Wiktor

Using lodash:

使用lodash

_.uniq('aaabbbccc').join(''); // gives 'abc'

回答by jayad aadrit

Try this if duplicate characters have to be displayed once, i.e., for i/p: aaabbbccc o/p: abc

如果重复字符必须显示一次,请尝试此操作,即对于 i/p:aaabbbccc o/p:abc

var str="aaabbbccc";
Array.prototype.map.call(str, 
  (obj,i)=>{
    if(str.indexOf(obj,i+1)==-1 ){
     return obj;
    }
  }
).join("");
//output: "abc"

And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e., for i/p: aabbbkaha o/p: kh

如果只需要显示唯一字符(字符串轰炸算法),请尝试此操作,添加另一个“和”条件以删除多次出现的字符并仅显示唯一字符,即对于 i/p:aabbbkaha o/p:千

var str="aabbbkaha";
Array.prototype.map.call(str, 
 (obj,i)=>{
   if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
     return obj;
   }
 }
).join("");
//output: "kh"

回答by Wade Helquist

<script>
    uniqueString = "";

    alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");

    function countChar(testString, lookFor) {
        var charCounter = 0;
        document.write("Looking at this string:<br>");

        for (pos = 0; pos < testString.length; pos++) {
            if (testString.charAt(pos) == lookFor) {
                charCounter += 1;
                document.write("<B>" + lookFor + "</B>");
            } else
                document.write(testString.charAt(pos));
        }
        document.write("<br><br>");
        return charCounter;
    }

    function findNumberOfUniqueChar(testString) {
        var numChar = 0,
            uniqueChar = 0;
        for (pos = 0; pos < testString.length; pos++) {
            var newLookFor = "";
            for (pos2 = 0; pos2 <= pos; pos2++) {
                if (testString.charAt(pos) == testString.charAt(pos2)) {
                    numChar += 1;
                }
            }
            if (numChar == 1) {
                uniqueChar += 1;
                uniqueString = uniqueString + " " + testString.charAt(pos)
            }
            numChar = 0;
        }
        return uniqueChar;
    }

    var testString = prompt("Give me a string of characters to check", "");
    var lookFor = "startvalue";
    while (lookFor.length > 1) {
        if (lookFor != "startvalue")
            alert("Please select only one character");
        lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
    }
    document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
    document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
    document.write("<br>" + uniqueString)
</script>

回答by Ahmad Adel

Here is the simplest function to do that

这是最简单的功能来做到这一点

  function remove(text) 
    {
      var unique= "";
      for(var i = 0; i < text.length; i++)
      {
        if(unique.indexOf(text.charAt(i)) < 0) 
        {
          unique += text.charAt(i);
        }
      }
      return unique;
    }