First, the array deduplication
1, two-cycle deduplication
var data = [1,2,4,3,5,2,1,3,2]
var newData = []
for(var i=0;i<data.length;i++) {
for(var j=i+1;j<data.length;j++) {
if (data[i] == data[j]) {
// j = i = i + 1
j = ++i
}
}
newData.push(data[i])
}
console.log(newData.sort())
Outside the loop is a time to take an array of values, in addition to which the loop is traversed back all values other than the value taken for comparison, if equal, comparing skipped circulation next round, if the current value does not find any equivalent the value is added to the new array
This is the value which takes an array of take-one comparison, if the value is in the back with an array of items inside, then I do not want this value, and so, in fact, take the last item in the array of this value, because this is the last one, and there can be no equal
2, two-cycle + splice deduplication
const arr = [1, 2, 3, 5, 4, 3, 2, 1];
for (var i=0;i<arr.length; i++) {
for (var j=i+1;j<arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j,1)
j--
}
}
}
console.log(arr)
// 打印结果
[1, 2, 3, 5, 4]
If the same value is determined by the double loop array, if the same value, the same will be removed after the value, method changes the original array splice, splice () method returns an array of values of segmentation, the original array is removed remaining value after the array values are divided out
For the community j--? Because the division, the original array length minus one, the last value of the down, diminished if j 1, j of the array which is on a value of, plus the look, equivalent skipped, it is necessary to subtract 1 It was then performed on a cycle value acquisition plus 1
3, loop closures + + the indexOf
var data = [1,2,4,3,5,2,1,3,2]
var newData = []
for(var i=0;i<data.length;i++) {
;(function () {
if (newData.indexOf(data[i]) === -1) {
newData.push(data[i])
}
})(i);
}
console.log(newData.sort())
By looping through the incoming cycle of the array index, and then indexOf
determine whether there are new array index value of the array, and if not, the array index value will be added to the new array inside
4, loop + object
var data = [1,2,4,3,5,2,1,3,2]
var newData = []
var obj = {}
for(var i=0;i<data.length;i++) {
if (!obj[data[i]]) {
obj[data[i]] = 1
newData.push(data[i])
}
}
console.log(newData.sort())
This method is to use the same object key
value can not be repeated, so by determining whether there is an object in the value of the current array index, and if not, this will be an array of values as key
to the object inside, by also adding value to the new array inside , if the object with this key
value and the array index is the same, is skipped
5, ES6 grammar -Set
var data = [1,2,4,3,5,2,1,3,2]
var newData = []
newData = new Set(data)
console.log(newData)
This is not to get to the bottom of the