preface

var repeatArr = [2, 1, 1, 10, 12, 5, 7, 7, 2, 1];
Copy the code

First: use the ES6 Set class

function repeatArrFn1(arr) {
    return Array.from(new Set(arr)); 
}
function repeatArrFn10(arr) { 
    return [...new Set(arr)]
}
Copy the code

Second: use the uniqueness of the object’s key name

function repeatArrFn2(arr) { var obj = {}; arr.forEach(num =>! obj[num] && (obj[num] = 1)); return Object.keys(obj).map(num =>+num); // The + sign here makes the string a number}Copy the code

Third: a layer of loop + array Api

function repeatArrFn3(arr) { var result = [],num; // arr.forEach(num => ! result.includes(num) && result.push(num)); arr.forEach(num => result.indexOf(num) === -1 && result.push(num)); // Return result; }Copy the code

Fourth: use array subscript to remove weight


 function repeatArrFn4(arr){
    return arr.filter((num,index)=>index === arr.indexOf(num)) 
 }

Copy the code

Fifth: double cycle

Function repeatArrFn5(arr) {var result = [],flag; function repeatArrFn5(arr) {var result = [],flag; for (var i = 0; i < arr.length; i++) { flag = true; for (var j = i + 1; j < arr.length; j++) { (arr[i] === arr[j]) && (flag = false); } flag && result.push(arr[i]); } return result; }Copy the code

Type 6: Sort by sort

function repeatArrFn6(arr) { var temp = arr.sort(); var result = [temp[0]]; For (var I = 1; i < temp.length; i++) { if (temp[i] ! == temp[i - 1]) { result.push(temp[i]); } } return result; }Copy the code