1. Set

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.

The members of the set method must be unique enough to meet our needs.

The code is as follows (example) :

let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6]; let unique = (arr) => [...new Set(arr)]; Console. log(unique(arr)) // Output: [1, 2, 3, 4, 6, 7] copy codeCopy the code

2. The reduce () method

Use the reduce method provided by the JS built-in object Array to reduce method use details can see my blog: Array common method code is as follows (example) :

let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6]; const res = arr.reduce((acc,cur) => { if(acc.indexOf(cur) === -1){ acc.push(cur) } return acc },[]) console.log(res) // Output: [1, 2, 3, 4, 6, 7] Copy codeCopy the code

3. Double for loop

J ==result.length = j= result.length = j= result.length = j= result.length = j= result.length = j= result.length

The code is as follows (example) :

let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6]; let result = []; for(var i = 0; i < arr.length; i++) { for(var j = 0 ; j < result.length ; j++) { if(arr[i] === result[j]){ break; }; }; if(j == result.length){ result.push(arr[i]); }; }; console.log(result); [1, 2, 3, 4, 6, 7] copies the codeCopy the code

4. The splice () method

Use the splice method provided by the built-in JS object Array

The code is as follows (example) :

let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6]; function unique(arr){ for(var i = 0; i<arr.length; i++){ for(var j = i+1; j < arr.length; j++){ if(arr[i] == arr[j]){ arr.splice(j, 1); j--; } } } return arr; } console.log(unique(arr)) copies the codeCopy the code

5. The filter () method

Use the splice method provided by the built-in JS object Array

The code is as follows (example) :

let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6] let unique = (arr) => { return arr.filter((item,index) => { return arr.indexOf(item) === index }) } Console. log(unique(arr)) // Output: [1, 2, 3, 4, 6, 7] copy codeCopy the code

6. Map

Map data structure is used for de-weighting

The code is as follows (example) :

let arr = [1, 2, 3, 4, 3, 2, 3, 4, 6, 7, 6] let unique = (arr)=> { let seen = new Map() return arr.filter((item) => { return ! Seen. Has (item) && Seen. Set (item,1)})} console.log(unique(arr)Copy the code

\