1. 数组去重 (利用includes检测是否存在 includes存在于数组当中返回true,不存在返回false )
var arr = [1, 1, 1, 1, 1, 1, 1, 11, 2, 3, 4, 85, 8, 8, 98, 968, 4, 56, 4, 5]
var newArr = []
for (let index = 0; index < arr.length; index++) {
if (newArr.includes(arr[index])) {
continue
}
newArr.push(arr[index])
}
2.和上个方法基本相同,只不过是把for循环换成了forEach,核心都是利用includes
var arr = [1, 1, 1, 1, 1, 1, 1, 11, 2, 3, 4, 85, 8, 8, 98, 968, 4, 56, 4, 5]
var newArr = []
arr.forEach(item => {
if (newArr.includes(item)) return
newArr.push(item)
});
3.利用双重for循环来进行一一比对,如果数据较多,可能存在性能上的问题
var arr = [1, 1, 1, 1, 1, 1, 1, 11, 2, 3, 4, 85, 8, 8, 98, 968, 4, 56, 4, 5]
var newArr = []
for (var i = 0; i < arr.length; i++) {
var item = arr[i]
for (var j = i + 1; j < arr.length; j++) {
if (item == arr[j]) {
arr.splice(j, 1)
j--
}
}
}
4.经典的去重方法,利用对象属性的唯一性
var arr = [1, 1, 1, 1, 1, 1, 1, 11, 2, 3, 4, 85, 8, 8, 98, 968, 4, 56, 4, 5]
var newArr = []
var obj = {}
for (var i = 0; i < arr.length; i++) {
var item = arr[i]
if (obj[item]) {
arr.splice(i, 1)
i--
continue
}
obj[item] = item
}
5.相当于是第四个的优化版 将数组的最后一个替换成当前删除的这个节省了所有的数组索引减一的情况
var arr = [1, 1, 1, 1, 1, 1, 1, 11, 2, 3, 4, 85, 8, 8, 98, 968, 4, 56, 4, 5]
var newArr = []
var obj = {}
for (var i = 0; i < arr.length; i++) {
var item = arr[i]
if (obj[item]) {
arr[i] = arr[arr.length - 1]
arr.length--
i--
continue
}
obj[item] = item
}
6.利用正则来去重
var arr = [1, 1, 1, 1, 1, 1, 1, 11, 2, 3, 4, 85, 8, 8, 98, 968, 4, 56, 4, 5]
var newArr = []
let str = arr.sort((a, b) => a - b).join('@') + '@'
let reg = /(\d+@)\1*/g
str.replace(reg, (n, m) => {
m = Number(m.slice(0, m.length - 1))
newArr.push(m)
})
7.利用se6的Set来去重