1. For loop traversal

Let arr =,2,3,4,5,6,1,3,5,2,4,6 [1]; for(let i = 0; i < arr.length; i++){ for(let j = i+1; j < arr.length; j++){ if(arr[i] === arr[j]){ arr.splice(j , 1); j--; }; };Copy the code

The two-layer for loop compares arr[I] to arr[I +1~arr.length], and splice(I +1,1) deweights if the same

2. Use IndexOfmethodsduplicate removal

Let arr =,2,3,4,5,6,1,3,5,2,4,6 [1]; let arr2 = []; for (let i = 0; i < arr.length; i++) { if (arr2.indexOf(arr[i]) === -1) { arr2.push(arr[i]); }; };Copy the code

The indexOf method returns -1 if it is not found

3, use the set method to remove the weight

Let arr =,2,3,4,5,6,1,3,5,2,4,6 [1]; function reset(arr){ return Array.from(new Set(arr)); }; let arr2 = reset(arr);Copy the code

A Set is similar to an array except that all its members are unique and cannot have duplicate values

4, Use the sort method to sort

Let arr =,2,3,4,5,6,1,3,5,2,4,6 [1]; arr = arr.sort(); let arr2 = []; for(let i = 0; i < arr.length; i++){ if(arr[i] ! == arr[i+1]){ arr2.push(arr[i]); }; };Copy the code

Sort the array first, and then compare the two items of the array to see if they are the same. If they are, add them to the new array using push

5. Use the includes method

Let arr =,2,3,4,5,6,1,3,5,2,4,6 [1]; let arr2 = []; for(let i = 0; i < arr.length; i++){ if(! arr2.includes(arr[i])){ arr2.push(arr[i]); }; };Copy the code

Similar to the indexOf method, includes checks for the presence of passed values in the array and returns true if they do

6. Use the filter method to remove the weight

Let arr =,2,3,4,5,6,1,3,5,2,4,6 [1]; let arr2 = arr.filter((item, i, self) => self.indexOf(item, 0) === i);Copy the code

Filter is an ES6 filter array method. Using filter combined with indexOf method can effectively remove weight