Array de-weight methodmethod One: Apply the Splice () method and the double-layer for loop (sort of a similar selection)function Norepeat (arr) {for (var i = 0;i < arr.length-1;i++) {for (var j = I+1;j<arr . length;j++) {if (arr[i] = = Arr[j]) {arr.splice (j,1);j--;}}} return arr; }Note: If you do not add j--, you will be removed, skipping a number
method A second way of writing inefficient, will increase a lot of useless cycle comparisonfunction Norepeat (arr) {var newArr = arr; for (var i = newarr.length;i > 0, i--) {for (var j = 0; j<i; j + +) {if (Newa Rr[i] = = Newarr[j]) {newarr.splice (i,1);
}}} return arr; }
method Two with ES5 new indexof () and push () method ( very simple and good understanding )function Norepeat (arr) {var newarr = []; for (var i in arr) {if (Newarr.indexof (arr[i]) = =-1) {Newarr.push (arr[i]); }} return newarr; }
method Three: First use sort sort to compare the adjacent equality, the same is deletedfunction Norepeat (arr) {Arr.sort (function (A, b) {return a-B;}); for (var i = 0; i < arr.length; i++) {if (arr[i] = = arr[i + 1]) {Arr.splice (I, 1);i--;}} return arr; }Note: If you do not add i--, you will be removed, skipping a number
method Four: The use of array subscript can not be repeated, the value of the parameter into an array of subscript, and then the subscript re-converted to a value (very good idea)function Norepeat (arr) {var newArr = []; var arrs = []; for (Var i=0;i<arr.length;i++) {var a = Arr[i]; Newarr[a] = 1; }
for (var i in NEWARR) {arrs[arrs.length] = i; Console.log (i); }
}
method Five can also be achievedvar arr = [6, 1, 1, 2, 1, 2, 1, 1, 3, 1, 1, 1, 4, 15]; function Norepeat (arr) {var arrcopy = []; for (var i = 0; i < arr.length; i++) {var count = 0;
for (Var j in Arrcopy) {if (arrcopy[j]! = Arr[i]) {count++;
}} console.log (Arrcopy); if (count = = arrcopy.length) {Arrcopy[arrcopy.length] = Arr[i]; }} return arrcopy; }
Five ways to de-weigh arrays in JS