1. Traversal Array method
It is the simplest method of array de-weight (indexof method)
Implementation ideas: Create a new array, traverse the array to be heavy, the value is not in the new array when the time (IndexOf-1) is added to the new array;
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;
}
2. Array subscript Judgment method
Call the IndexOf method, performance and Method 1 almost
Implementation idea: If the current array of item I is in the current array the first occurrence of the position is not I, then the term I is repeated, ignored. Otherwise, the result array is deposited.
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;
}
3. Post-sorting adjacent removal method
Implementation ideas: Sort incoming arrays, sort the same values next to each other, and then iterate over the sorted array, adding only values that do not duplicate the previous value.
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;
}
4. Optimized traversal array method (recommended)
Realization idea: Double loop, outer loop represents from 0 to arr.length, inner loop means from i+1 to Arr.length
Put the right value that is not duplicated in the new array. (The next round of judgment that terminates the current loop and enters the outer loop when a duplicate value is detected)
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;
}
5.ES6 implementation
Basic idea: ES6 provides a new set of data structures. It is similar to an array, but the values of the members are unique and have no duplicate values.
The SET function can accept an array (or an array-like object) as an argument for initialization.
function Unique5 (arr) { var x = new Set (arr); return [... x];}
Extended: If repeated, the element is removed
Array subscript de-weight
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;
}
Several methods of array de-weight