• Use the indexof() method

Note: The indexof() method is case-sensitive

  1. The indexOf() method returns the indexOf the element when it first appears in the array and compares it.
function unique(arr){
    let newArr = [];
    for(let i = 0; i < arr.length; i++){
    // arr.indexof (arr[I]) returns the indexOf the first occurrence of the element in arr, so if equal to I
    // The element is pushed to newArr for the first time
        if(arr.indexOf(arr[i]) === i){ newArr.push(arr[i]); }}return newArr;
}
console.log(unique([2.45.66.23.'a'.2.66.'a'.54.23.2.1])) //[2, 45, 66, 23, "a", 54, 1]
Copy the code

IndexOf () returns -1 if the string value to be retrieved is not present

function unique2(arr){
    let newArr=[];   
    for(var i=0; i<arr.length; i++){if(newArr.indexOf(arr[i])===-1) {// Check if it contains the elementnewArr.push(arr[i]); }}return newArr;
}
console.log(unique2([4.5.2.3.3.4.6]));
Copy the code
  • ES6 new constructor Set

Elements in a Set occur only once, that is, the elements in a Set are unique. With natural weight removal function

let arr = [4.1.2.2.3.2.1.4.4];
let set = new Set(arr);
console.log(set);/ / {4, 1, 2, 3}
console.log(... set);/ / 1 2 3 4
console.log([...set]);/ / [4, 1, 2, 3]
Copy the code