1. Traversal number group method

It’s the simplest way to de-duplicate an array (indexOf)

Create an array, iterate over the array to be duplicated, and add it to the new array when the value is not in the new array (indexOf -1).

Var arr =,8,5,0,5,2,6,7,2 [2];function arrayRemoval(arr){
  var hash= [];for (var i = 0; i < arr.length; i++) {
     if(hash.indexOf(arr[i])==-1){ hash.push(arr[i]); }}return hash;
}
Copy the code

2. Array subscript judgment method

The indexOf method is called, with similar performance to method 1

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 arrayRemoval(arr){
  var hash= [];for (var i = 0; i < arr.length; i++) {
     if(arr.indexOf(arr[i])==i){ hash.push(arr[i]); }}return hash;
}
Copy the code

3. Adjacent division after sorting

Sort the array, the same values will be adjacent, and then when traversing the sorted array, the new array will only add values that do not duplicate the previous value.

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

4. Optimization of traversal number group method (recommended)

The outer loop represents from 0 to arr.length, and the inner loop represents from I +1 to arr.length

Place the unduplicated right-hand values in the new array. (Terminate the current cycle and enter the next round of judgment of the outer cycle when duplicate values are detected)

function arrayRemoval(arr){
  var hash= [];for (var i = 0; i < arr.length; i++) {
    for (var j = i+1; j < arr.length; j++) {
      if(arr[i]===arr[j]){
        ++i;
      }
    }
      hash.push(arr[i]);
  }
  return hash;
}
Copy the code

5. ES6 implementation

Basic idea: ES6 provides a new data structure called 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. Array.from: Creates a new Array instance from an array-like or iterable

function arrayRemoval(array) {
  return Array.from(new Set(array));
}

Copy the code