Home  >  Article  >  Web Front-end  >  JS implements string and array deduplication method

JS implements string and array deduplication method

php中世界最好的语言
php中世界最好的语言Original
2018-04-27 14:02:531842browse

This time I will bring you js implementation String and array deduplication methods, js implementation of string and array deduplication What are the precautions , the following is a practical case, Let’s take a look.

The example in this article describes the method of JS to implement string deduplication and array deduplication. Share it with everyone for your reference, the details are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js数组、字符串去重</title>
</head>
<body>
  <script type="text/javascript">
  /*数组去重*/
    function quchong(arr){
      var len = arr.length;
      arr.sort();
      for(var i=len-1;i>0;i--){
        if(arr[i]==arr[i-1]){
          arr.splice(i,1);
        }
      }
      return arr;
    }
    var a = ["a","a","b",'b','c','c','a','d'];
    var b = quchong(a);
    console.log(b);
  /*字符串去重*/
  function quchongstr(str){
    var a = str.match(/\S+/g);//等价于str.split(/\s+/g)// \s空白符,\S非空白符
    a.sort();
    for(var i=a.length-1;i>0;i--){
      if(a[i]==a[i-1]){
        a.splice(i,1);
      }
    }
    return a.join(" ");
  }
  var str = quchongstr("a a b a b e");
  console.log(str);
  </script>
</body>
</html>

Running results:

I believe you have mastered the method after reading the case in this article, please come for more exciting information Pay attention to other related articles on php Chinese website!

Recommended reading:

What are the differences between using for loop var and using let in jQuery

JS calling mode and this Detailed explanation of keyword usage

The above is the detailed content of JS implements string and array deduplication method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn