An array of several ways commonly used deduplication

Method 1: iterate
var arr = [ "c",A "," X "];
var newArr = [];
for (var I = 0; I <arr.length; I ++) {
IF (newArr.indexOf (ARR [I]) === -1) {
// does not exist, add to the newArr
newArr.push (ARR [I]);
}
}
the console.log (newArr);
ideas:
traversing ARR, see arr [i], in the presence or absence of a value of -1 indexOf newArr, the description does not exist
(1) If there is not, in newArr added to
(2), if present, do not control


Method 2: array subscript deduplication method
var arr = [ "c",X "," A "," X "];
var newArr = [];
for (var I = 0; I <arr.length; I ++) {
IF (arr.indexOf (ARR [I]) == I) {
newArr.push (ARR [i]);
}
}
the console.log (newArr);
mind: if the i-th position of the first term appears in the current in the current array of the array
is i, represents the first time, into a new the array
is not i, so i represents the item is repeated, ignored

indexOf to find value in the array of the first occurrence of the subscript


Method 3: Method sorted adjacent to heavy
var arr = [ "c","the X-", "A", "the X-"];
arr.sort ();
// console.log (arr);? // [ "A", "A", "A", "A", "A "," C "," C "," X "," X "," X "," Z "," Z "]
var newArr = [ARR [0]];
for (var I =. 1, len = ARR .length; I <len; I ++) {
! IF (ARR [I] == newArr [newArr.length -. 1]) {
newArr.push (ARR [I]);
}
}
the console.log (newArr);
ideas:
incoming sorted, the same elements will be adjacent
to create a new array and arr [0];
then traverse the array, the last element of the new array values are compared, if different from the addition of the new array.

 

Method 4: iterate the optimization method
var arr = [1, 3,

for (var I = 0; I <arr.length; I ++) {
for (var = I + J. 1; J <arr.length; J ++) {
IF (ARR [I] == ARR [J]) {
ARR. splice (J,. 1);
J,;
}
}
}
the console.log (ARR) // [1,3,4,5,8,9]

ideas:
traversing the array passed, the element by element comparison right turn ,
if the element has duplicate, delete duplicate elements to the right,
if the element does not repeat elements and the right, i.e. out of the inner loop; the next element as the comparison object

Guess you like

Origin www.cnblogs.com/yeanling/p/10943033.html