Home > Web Front-end > JS Tutorial > body text

How to implement string deduplication and array deduplication using JS

不言
Release: 2018-04-21 16:16:38
Original
3066 people have browsed it

This article mainly introduces the method of JS to achieve string deduplication and array deduplication, involving JavaScript's traversal, judgment, deletion, addition and other related operation skills for strings and arrays. Friends in need can refer to it

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>www.jb51.net 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",&#39;b&#39;,&#39;c&#39;,&#39;c&#39;,&#39;a&#39;,&#39;d&#39;];
    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>
Copy after login

Running results:

Related recommendations:

js implements front-end and backend transmission of Json

js implements character limit Chinese characters = two characters

js Implement string to date format

#

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template