An array of six methods deduplication

1. double loop through

the unique1 function (ARR) {
// iterate ARR
for (var I = 0, R & lt = []; I <arr.length; I ++) {
// iterate R & lt
for (var J = 0; J <r.length; ++ J) {
// if the element r is equal to the current traversing the element of arr loop exits
IF (r [J] == arr [I]) {
BREAK;
}
}
// if not found last traversed with the current arr elements of the same element
IF (J == r.length) {
// put this element appended to the
R & lt [r.length] = ARR [I];
}
}
return R & lt;
}

2. Use the hash array way

the unique2 function (ARR) {
// iterate ARR
for (var I = 0, the hash = [], R & lt = []; I <arr.length; I ++) {
// If the hash does not exist in the array arr [i ] of the underlying variable
IF (the hash [ARR [I]] === undefined) {
// this value into the final array
R & lt [r.length] = ARR [I];
// and this value as the next hash table array storage, a custom value to
the hash [ARR [I]] =. 1;
}
}
return R & lt;
}

3. Object

unique3 function (ARR) {
// the algorithm consistent with the second embodiment, because the underlying object storage is an array
var obj = {};
// iterate
for (var i = 0, r = []; i <arr.length; I ++) {
// if obj is not present in the current attribute value of the attribute name arr
! IF (obj [arr [I]]) {
// this value into the final array
r. Push (ARR [I]);
// and this value as the hash table array storage, a self-defined value to the
obj [ARR [I]] =. 1;
}
}
return R & lt;
}

4. Sort the array give

unique4 function (ARR) {
// sort to ARR
arr.sort (function (A, B) {return ab &})
// iterate
for (var. 1 = I; I <arr.length; I ++) {
// if the current value is equal to the preceding value of the
IF (ARR [I] === ARR [-I. 1]) {
// delete the value
arr.splice (I,. 1);
// deleted as a value, to the need to cycle before moving a
i--;
}
}
return ARR;
}

5. By subscript

unique5 function (arr) {
// iterate
for (var I = 0; I <arr.length; I ++) {
// iterate to find arr current equal to the value
for (var j = i + 1 ;;) {
// record found subscript j
j = arr.indexOf (ARR [I], j);
// if j is -1, the same value as representing no behind the
IF (j == -1) {
BREAK;
}
// delete the value
arr.splice (J,. 1);
}
}
return ARR;
}

6.

unique6 function (ARR) {
// new syntax for ES6
return the Set new new (ARR);
}

was arr = [5,4,9,1,6,8,7,5,4,2,4,5,6,4,2,6,4,2,1,5,9]

Guess you like

Origin www.cnblogs.com/hyh888/p/11502860.html