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

What are the methods to achieve array deduplication in js? A brief introduction to js array deduplication method

不言
Release: 2018-08-11 15:46:20
Original
1823 people have browsed it

There are many ways to remove duplicate data from js arrays. Today’s article brings you three methods to remove duplicate data from js arrays. It has certain reference value. Friends in need can refer to it. Hope it helps.

One of the js array deduplication methods: Object simulation HashMap traversal and deduplication

function duplicates(arr) {
    var newArr=[]
    var newArr1=[]
    for(var i = 0;i<arr.length;i++){
       for(var j=0;j<arr.length;j++){
           if(i!=j){
               if(arr[i]==arr[j]){
                   newArr.push(arr[i])
               }
           }
       }
    }
        var json={}
        for(var i = 0; i < newArr.length; i++){
            if(!json[newArr[i]]){
                newArr1.push(newArr[i]);
                json[newArr[i]] = 1;
            }
        }
        return newArr1

}
Copy after login

The second js array deduplication method: Set the gate flag, according to conditions Deduplication

function duplicates(arr) {
    var newArr=[]
    var newArr1=[]
    for(var i = 0;i<arr.length;i++){
       for(var j=0;j<arr.length;j++){
           if(i!=j){
               if(arr[i]==arr[j]){
                   newArr.push(arr[i])
               }
           }
       }
    }
       
    newArr1.push(newArr[0])
    for(var i=0;i<newArr.length;i++){
        var flag=0
        for(var j=0;j<newArr1.length;j++){
            if(newArr[i]==newArr1[j]) flag=1

        }
        if(flag==0) newArr1.push(newArr[i])
     }
        return newArr1

}
Copy after login

The third method to deduplicate js arrays: ES6, set collection deduplication

function duplicates(arr) {
   let newArr = arr;
   arr = [];
   let set = new Set();
   set(newArr);
   for (let i of set){
   arr.push(i);
  }
   return arr;
}
Copy after login

Related recommendations:

JS Array Removal of Duplicate Data

JS Array Removal Detailed Graphics and Text

js 4 ways to remove duplication from arrays

The above is the detailed content of What are the methods to achieve array deduplication in js? A brief introduction to js array deduplication method. 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