To summarize the methods of array deduplicating in JS:

1. Traversal number group method (indexOf)

Initializes an array, iterates through the array to be duplicated, and adds to the new array when the value is not in the new array (indexOf -1).

 var arr=[1.4.6.9.2.4.3.9.0.0];
  function unique1(arr){
    var newarr=[];
    for (var i = 0; i < arr.length; i++) {
      if(newarr.indexOf(arr[i])==-1){ newarr.push(arr[i]); }}return newarr;
  }
  console.log(unique1(arr));  // [1, 4, 6, 9, 2, 3, 0]
Copy the code

2. Array subscript judgment 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 newarr=[];
    for (var i = 0; i < arr.length; i++) {
      if(arr.indexOf(arr[i])==i){ newarr.push(arr[i]); }}return newarr;
  }
  console.log(unique2(arr)); // [1, 4, 6, 9, 2, 3, 0]
Copy the code

Original link: blog.csdn.net/qq_41999617…