js array deduplication algorithm (reproduced)

The following may duplicate parts, the project is useful, but not more anxious to sort out and verify. 

 

A: https: //www.cnblogs.com/jiayuexuan/p/7527055.html

1. iterate method

It is the most simple array deduplication method (indexOf method)

Realization of ideas: a new array to traverse the array to be heavy, when a new value is not in the array (the indexOf -1) was added to the new array;

Copy the code
var arr=[2,8,5,0,5,2,6,7,2];
function unique1(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. Analyzing Method array subscript

Call indexOf method, performance, and almost 1

Realization of ideas: if the current array of item i for the first time in the current array position i is not, then i represents the item is repeated, ignored. Otherwise, the result is stored in an array.

Copy the code
function unique2(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. Sort the adjacent removal method 

Realization of ideas: to sort the array passed, after ordering the same value will be adjacent, then traverse an array after sorting, adding only new array does not overlap with the previous value.

Copy the code
function unique3(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. iterate the optimization method (Reference)

Realization of ideas: double loop, outer loop represents from 0 to arr.length, the cycle represents the i + 1 to arr.length

Will not duplicate the right values ​​into a new array. (Detected at a current cycle terminates when the outer loop repeats the same time into the value of the judgment)

Copy the code
function unique4(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


An attribute name can go for heavy array

unique4 function (ARR, name) { 
  var the hash = []; 
  for (var I = 0; I <arr.length; I ++) { 
    for (var = I + J. 1; J <arr.length; J ++) { 
      IF ( ARR [I] [name] === ARR [J] [name]) { 
        ++ I; 
      } 
    } 
      hash.push (ARR [I] [name]); // not want to keep the value of other attributes was added [ name] 
  } 
  return the hash; 
}

  

5.ES6 achieve

The basic idea: ES6 provides a new data structure Set. It is similar to an array, but the value of the member is unique, no duplicate values.

Set function can accept an array (or array-like objects) as parameters, it is used to initialize.

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

 Extended: If repeated, this element is removed

Array subscript deduplication

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

 

Two: https: //www.cnblogs.com/wteam-xq/p/4732351.html

 1. iterate method

  The easiest method to weight,  the realization of ideas: Create a new array, the array passed to traverse, value is not added to the new array to the new array ; pay attention to the point : to determine whether the value in an array of methods "indexOf" method is ECMAScript5, IE8 less does not support, the need to write more compatible with low version of browser code, source code is as follows:

Copy the code
The simplest array // Method to weight 
function the unique1 (Array) { 
  var n-= []; // a new temporary array 
  // iterate current array 
  for (var I = 0; I <be array.length; I ++) { 
    // If the current array of i saved into a temporary array, skip, 
    // otherwise the current term push to temporary array inside 
    if (n.indexOf (array [i] ) == -1) n.push (array [ I]); 
  } 
  return n-; 
}
Copy the code
Copy the code
// determine whether the browser supports indexOf, indexOf new method ecmaScript5 IE8 or less (including IE8, IE8 supports only part ecma5) does not support the 
IF (! Array.prototype.indexOf) { 
  // add indexOf method 
  Array.prototype.indexOf = function (Item) { 
    var Result = -1, a_item = null; 
    IF (this.length == 0) { 
      return Result; 
    } 
    for (var I = 0, len = this.length; I <len; I ++) { 
      a_item the this = [I]; 
      IF (a_item === Item) { 
        Result = I; 
        BREAK; 
      }   
    } 
    return Result; 
  } 
}
Copy the code

 

2. A method for object key

  The method of execution speed faster, than any other method is to take up some of the memory; the realization of ideas: New js objects and a new array, while traversing the incoming array to determine whether the value for the js object's key, is not the case for new objects increase the key and put in a new array. Precautions:  determining whether the object is a key js performed automatically on incoming key "toString ()", different keys may be mistaken as; for example: a [1], a [ "1"]. To solve the problems still have to call the "indexOf".

Copy the code
// fastest, comprise up space (space for time) 
function the unique2 (Array) { 
  var n-= {}, R & lt = [], len = be array.length, Val, type; 
    for (var I = 0; I < be array.length; I ++) { 
        Val = Array [I]; 
        type = typeof Val; 
        IF (n-[Val]) {! 
            n-[Val] = [type]; 
            r.push (Val); 
        } the else IF (n-[ Val] .indexOf (type) <0) { 
            n-[Val] .push (type); 
            r.push (Val); 
        } 
    } 
    return R & lt; 
}
Copy the code

 

3.  

  Still have to call the "indexOf" method performance with almost 1, the realization of ideas : if the current array of item i for the first time in the current array position i is not, then i represents the item is repeated, ignored. Otherwise, the result is stored in an array.

Copy the code
unique3 function (Array) { 
  var n-= [Array [0]]; // results array 
  // traversing from the second 
  for (var. 1 = I; I <be array.length; I ++) { 
    // if the current array item i first appeared in the current array position is not i, 
    // so i represents the item is repeated, ignored. Otherwise, the resulting array into 
    IF (The Array.indexOf (Array [I]) == I) n.push (Array [I]); 
  } 
  return n-; 
}
Copy the code

 

4.  

  Although the "sort" an array of native method to sort the results less reliable, but do not pay attention to the shortcomings in the re-order of no effect. Realization of ideas: to pass an array of sorting, the sorted adjacent to the same value, then only join a new array of non-repetition of the previous value while traversing.

Copy the code
// The same values of adjacent, then traverse value deduplication 
function unique4 (Array) { 
  Array.sort (); 
  var = Re [Array [0]]; 
  for (var. 1 = I; I <be array.length; I ++ ) { 
    ! IF (Array [I] == Re [-re.length. 1]) 
    { 
      re.push (Array [I]); 
    } 
  } 
  return Re; 
}
Copy the code

 

The optimization method iterate

  From foreign Bowen , the method of implementation code is quite cool; the realization of ideas : get not repeat the rightmost values into a new array. (Detected at a current cycle terminates when entering the top loop is repeated while the value of the judgment)

Copy the code
@ Idea: Get not duplicate a value into a new rightmost array 
function unique5 (Array) { 
  var R & lt = []; 
  for (var I = 0, L = be array.length; I <L; I ++) { 
    for ( = I + J. 1 var; J <L; J ++) 
      IF (Array [I] === Array [J]) J = I ++; 
    r.push (Array [I]); 
  } 
  return R & lt; 
}
Copy the code

 

demo Minamoto码

 

Three: https: //www.jianshu.com/p/79fe3489600f

1. Method iterate
easiest method to re-realize the idea: Create a new array, the array incoming traversal, the new value is not added to the new array to array; Note points: In the process of determining whether the value of the array "indexOf" is ECMAScript5 method, IE8 does not support the need to write more compatible with low version of browser code, source code is as follows:

var arr = [1,3,5,7,9,1,9,5,9,3,5,11,13]; function unique1(array){ var newArr=[];//新建一个新数组 //遍历参数数组array for(var i=0;i<array.length;i++){ //判断新数组是否有这个元素值,没有的话,就把arr[i]给push到新数组newArr中 if(newArr.indexOf(array[i])===-1){ newArr.push(arr[i]); } } return newArr; } console.log(unique1(arr)); 

Results are as follows:

 
Pictures .png

2. The object key for law
than almost any other method, is occupied by a large number of memory speed of the method of execution, realization of ideas: Create a new js objects and arrays, passed in traversing the array, it is determined whether the value of the object js key, if not the key to add to the object and put in a new array. Precautions: js is determined whether the target key, automatically performs the incoming key "toString ()", different keys may be mistaken as; for example: a [1], a [ "1"]. To solve the problems still have to tune "indexOf".

var arr = [1,3,5,7,9,1,9,5,9,3,5,11,13]; // 速度最快, 占空间最多(空间换时间) function unique2(array){ var json={},newArr=[],val,type; for(var i=0;i<array.length;i++){ val=array[i]; //判断val是什么数据类型 type=typeof val; console.log("判断类型"+[type]); //判断值是否为js对象的键,不是的话给对象新增该键并放入新数组 if(!json[val]){ json[val]=[type]; newArr.push(val); } else if(json[val].indexOf(type)<0){ json[val].push(type); newArr.push(val); } } return newArr; } console.log(unique2(arr)); 

Results are as follows:

 
Pictures .png

3. The array subscript law judge
still have to call the "indexOf" method performance with almost 1, the realization of ideas: if item i of the first occurrence of the current array current array is not i, so i represents the item is duplicated , ignored. Otherwise, the result is stored in an array.

var arr = [1,3,5,7,9,1,3,5]; function unique3(array){ var n = [array[0]]; //结果数组 //从第二项开始遍历 for(var i = 1; i < array.length; i++) { //如果当前数组的第i项在当前数组中第一次出现的位置不是i, //那么表示第i项是重复的,忽略掉。否则存入结果数组 if (array.indexOf(array[i]) == i) n.push(array[i]); } return n; } console.log(unique3(arr)); 

Results are as follows:

 
Pictures .png

4. Sorting adjacent removal method
although "sort" native array very reliable method of sorting results, but do not pay attention in order to weight the drawback no effect. Realization of ideas: to pass an array of sorting, the sorted adjacent to the same value, then only join a new array of non-repetition of the previous value while traversing.

var arr = [1,3,5,7,9,1,3,5]; function unique4(array){ array.sort(); var re=[array[0]]; for(var i = 1; i < array.length; i++){ if( array[i] !== re[re.length-1]){ re.push(array[i]); } } return re; } console.log(unique4(arr)); 
 
Pictures .png

The optimization process through the array
to achieve code of the method is quite cool, to realize the idea: Get not duplicate a value into a new rightmost array. (Detected terminates the current cycle is repeated when the value at the same time into a top loop determination) Recommended


// 思路:获取没重复的最右一值放入新数组 
var arr = [1,3,5,7,9,1,3,5]; function unique5(array){ var r = []; for(var i = 0, l = array.length; i < l; i++) { for(var j = i + 1; j < l; j++) if (array[i] === array[j]) j = ++i; r.push(array[i]); } return r; } console.log(unique5(arr)); 

Results are as follows:


 
Pictures .png

6. By hash table
ideas are as follows:
hash is an object of the present key (key: value), but now is empty, the hash [Key] = value;
. 1: I = 0; the this [I] = this [0] = 1; hash [this [0]] = hash [1], since the hash is initially empty, no 1 = key value is found, then it is undefined,
2: hash [1] = to true (case a first set of objects have a hash value pairs), the number of the first array to the new original array, repeat Step
3: because the hash value does not repeat the determination is undefined, as are repeated true, so do not repeat are added to the new array
4: because the value of the hash table is stored in the memory address on the heap memory, so the number of non-repetition of elements, the number of memory necessary to store points, this method is so much memory, but in contrast, the operation of this movement is the fastest,
5: this is the space of time in exchange for a small amount of data, this method is recommended

var arr = [1,'b','b',4,3,3,4,5,1]; Array.prototype.unique2 = function(){ var hash = {}; //定义一个hash表 var arr1 = []; //定义一个新数组 for(var i=0;i<this.length;i++){ if(! hash[this[i]]){ hash[this[i]] = true; arr1.push(this[i]); } } return arr1; } console.log(arr); console.log(arr.unique2()); 

Results are as follows:

 
 


 

Guess you like

Origin www.cnblogs.com/hao-1234-1234/p/11122383.html