基于Set
- 将数组转为Set(set自身带有去重功能)
- 再将set转为数组
let arr = [1, 2, 3, 2, 2, 3, 1, 7, 8, 3, 9, 4];
let newArr = Array.from(new Set(arr));
console.log(newArr)
基于indexof
- 将数组每一项与后面所有项比较
- 如果后面所有项中不存在当前项,则将其添加到新数组当中
let arr = [1, 2, 3, 2, 2, 3, 1, 7, 8, 3, 9, 4];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let item = arr[i],
args = arr.slice(i + 1);
if (args.indexOf(item) == -1) {
newArr.push(item)
}
}
console.log(newArr)
基于键值对
- 把数组中所有项以键值对形式插入obj当中
- 在插入前判断obj中是否已存在当前键值对
- 如果已存在则将数组中当前项用最后一项替换,并将数组长度减一,已循环次数减一
- 否则向obj中插入当前键值对
let arr = [1, 2, 3, 2, 2, 3, 1, 7, 8, 3, 9, 4];
let obj = {};
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (typeof obj[item] !== 'undefined') {
arr[i] = arr[arr.length - 1];
arr.length--;
i--;
}
obj[item] = item;
}
obj = null;
console.log(arr)
基于正则(先排序,后相邻比较)
let arr = [1, 2, 3, 2, 2, 3, 1, 7, 8, 3, 9, 4];
arr.sort((a, b) => a - b);
arr = arr.join('@') + '@';
let reg = /(\d+@)\1*/g;
let ary = [];
arr.replace(reg, (val, group) => {
let m = parseFloat(group);
ary.push(m)
})
console.log(ary)