First of all in the array to redo, we want to create an array, this according to their own ideas to create OK! IndexOf method, call indexOf method, adjacent division after sorting, optimization traversal number group method, ES6 implementation…

Here is an arbitrary array we created

var ary = [1, 3, 2, 2, 3, 5, 1, 15, 51, 41, 214, 51, 5, 45, 15, 4, 854, 5, 6]
Copy the code

Method indexOf

Iterates through the array to be reloaded, adding the value to the new array when it is not (indexOf -1).

function unique1(arr){
  var temp=[];
  for (var i = 0; i < arr.length; i++) {
     if(temp.indexOf(arr[i])==-1){
     temp.push(arr[i]);
     }
  }
  return temp;
}
Copy the code

Call the indexOf method

If the first occurrence of the i-th item in the current array is not I, then the i-th item is repeated and ignored. Otherwise, store the result array. function unique2(arr){ var temp=[]; for (var i = 0; i < arr.length; i++) { if(arr.indexOf(arr[i])==i){ temp.push(arr[i]); } } return temp; }Copy the code

Use indexOf and lastIndexOf for de-weighting

Function unique3(arr) {return indexOf (arr); return indexOf (arr); return indexOf (arr); i < ary.length; i++) { var n = arr.indexOf(arr[i]), m = arr.lastIndexOf(arr[i]); if (n ! == m){ arr.splice(m,1); // If n and m are different, m is a duplicate item and you only need to delete it. I --; } } return arr; }Copy the code

Double for loop (Optimization traversal number group method)

Splice () for (var I = 0; i < ary.length; i++) { var temp = ary[i]; for (var j = i + 1; j < ary.length; j++) { if (temp === ary[j]) { ary.splice(j, 1); // Array collapse. Splice changes array length, so subtract j from j--; }}}Copy the code

The name of the property used by the object cannot be repeated

function unique2(arr) { var obj = {}; arr.forEach(function (v) { obj[v] = v ; // obj[1] = 1; }) console.log(obj); if v stands for 1, add a key-value pair to obj with a property name of 1 and a property value of 1}) console.log(obj); // Put the key-value pairs stored in the object into the new array, and return the new array; var arr = []; for (var k in obj) { arr.push(obj[k]) } return arr; }Copy the code

Sorting adjacent division

We sort the array, and the same values are adjacent, and when we iterate over the sorted array, the new array adds only values that do not duplicate the previous one.

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

ES6 implementation

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 Set function can take an array (or an array-like object) as an argument for initialization.

    function unique5(arr){
      var x = new Set(arr);
     return [...x];
    }
Copy the code

.