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

Introduction to three methods to remove duplicates from arrays in JavaScript

怪我咯
Release: 2017-07-07 15:07:04
Original
1104 people have browsed it

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"]
Copy after login

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"]
Copy after login

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"]
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!