Home >Web Front-end >JS Tutorial >Introduction to three methods to remove duplicates from arrays in JavaScript

Introduction to three methods to remove duplicates from arrays in JavaScript

怪我咯
怪我咯Original
2017-07-07 15:07:041162browse

This article introduces you to js through three methodsArrayThe method of removing duplicates is very practical. Friends who are interested can learn together

No more nonsense, specific methods As shown below:

Method 1: Return the new array and the type of each bit has not changed

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"]

Method 2: Similar to method one, but Bennon feels that method one 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"]

Method three: easier to understand than the first two but returns a new array every time The number type of seats has been changed to string type! ! It has to be dealt with at the critical moment

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"]

The above is the detailed content of Introduction to three methods to remove duplicates from arrays in JavaScript. 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