Home > Web Front-end > JS Tutorial > Three ways to remove duplicates from arrays in JavaScript_javascript tips

Three ways to remove duplicates from arrays in JavaScript_javascript tips

WBOY
Release: 2016-05-16 15:04:30
Original
1211 people have browsed it

No more nonsense, the specific method is as follows:

Method 1: Return the new array and the type of each bit remains unchanged

function outRepeat(a){
      var hash=[],arr=[];
      for (var i = 0; i < a.length; i++) {
        hash[a[i]]!=null;
        if(!hash[a[i]]){
          arr.push(a[i]);
          hash[a[i]]=true;
        }
      }
      console.log(arr);
    }
    outRepeat([2,4,4,5,"a","a"]);//[2, 4, 5, "a"] 
Copy after login

Method 2: Similar to method 1, but I think method 1 is easier to understand

function outRepeat(a){
      var hash=[],arr=[];
      for (var i = 0,elem;(elem=a[i])!=null; i++) {
        if(!hash[elem]){
          arr.push(elem);
          hash[elem]=true;
        }
      }
      console.log(arr);
    }
    outRepeat([2,4,4,5,"a","a"]);//[2, 4, 5, "a"] 
Copy after login

Method 3: Easier to understand than the first two, but the number type of each position in the returned new array changes to string type! ! Critical moments have to be dealt with

function outRepeat(a){
      var hash=[],arr=[];
      for (var i = 0; i < a.length; i++) {
        hash[a[i]]=null;
      }
      for(var key in hash){
          arr.push(key);        
        }
      console.log(arr);
    }
    outRepeat([2,4,4,5,"a","a"]);//["2", "4", "5", "a"]
Copy after login

The above are the three methods that the editor introduced to you to remove duplicates from arrays in JavaScript. I hope it will be helpful to you!

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