1,es6 set
ES6 provides a new Set of data structures. It is similar to an array, but the values of the members are unique and there are no duplicate values.
let arr = [1,2,3,4,3,2,3,4,6,7,6]; let unique = (arr)=> [...new Set(arr)]; unique(arr);//[1, 2, 3, 4, 6, 7]
2,es6 map
The idea is that if there is no attribute of array element in the map object, add the attribute of array element in the map object, assign the value to 1, and then filter.
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); }); }; unique(arr);
3. for double cycle
By judging whether the second level loop contains this element in the de duplicated array, if there is one, exit the second level loop. If there is no j==result.length, it will be equal, and then add the corresponding element to the last array.
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);
4,indexOf
The indexOf() method returns the first occurrence of a specified element in an array. If not, return - 1.
let arr = [1,2,3,4,3,2,3,4,6,7,6]; let unique = (arr) => { let result = []; for( var i = 0 ; i < arr.length ; i++){ if(result.indexOf(arr[i]) == -1){ result.push(arr[i]) } }; return result; }; unique(arr);
5,indexOf filter
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; }) }; unique(arr);
6. De duplication after sorting
First, sort the array, and then judge whether it is the first element and whether the previous element is the same as the next element. Different elements are added to the new array
let arr = [1,2,3,4,3,2,3,4,6,7,6]; let unique = (arr) => { let arrNew = arr.sort((a,b)=>a-b); let seen,result = []; for(var i = 0 ; i < arrNew.length ;i++){ if(!seen || seen != arrNew[i]){ result.push(arrNew[i]); }; seen = arrNew[i] }; return result; }; unique(arr);