1、利用排序后,再去重
// 1、利用排序后,再去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 5, 6, 7, 5]
// 1.1利用sort拍讯
arrList.sort((a, b) => { return a - b })
// 1.2利用冒泡排序
// for (let i = 0; i < arrList.length; i++) {
// for (let j = i + 1; j < arrList.length; j++) {
// if (arrList[i] > arrList[j]) {
// let temp = arrList[i];
// arrList[i] = arrList[j];
// arrList[j] = temp;
// }
// }
// }
let newArrList = [];
for (let i = 0; i < arrList.length; i++) {
if (arrList[i] != arrList[i + 1]) {
newArrList.push(arrList[i])
}
}
2、双重for循环去重
// 2、双重for循环去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5]
for (let i = 0; i < arrList.length; i++) {
for (let j = i + 1; j < arrList.length; j++) {
if (arrList[i] === arrList[j]) {
arrList.splice(j, 1);
j--
}
}
}
3、利用indexof去重
// 3、利用indexof去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
let newArrList = [];
for (let i = 0; i < arrList.length; i++) {
if (newArrList.indexOf(arrList[i]) === -1) {
newArrList.push(arrList[i])
}
}
4、利用对象属性去重
// 4、利用对象属性去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
let obj = {};
for (let i = 0; i < arrList.length; i++) {
if (!obj[arrList[i]]) {
obj[arrList[i]] = arrList[i]
}
}
5、利用es6的new Set()配合...展开语法去重
// 5、利用es6的new set()配合...展开语法去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
console.log([...new Set(arrList)])
6、利用es6的new Set()配合Array.from()去重
// 6、利用es6的new Set()配合Array.from()去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
console.log(Array.from(new Set(arrList)))
7、利用数组的includes方法
// 7、利用数组的includes方法
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
let newArrList = [];
for (let i = 0; i < arrList.length; i++) {
if (!newArrList.includes(arrList[i])) {
newArrList.push(arrList[i])
}
}
8、利用数组的filter()+indexOf()
// 8、利用数组的filter()+indexOf()
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
let newArrList = arrList.filter((item, index) => {
return arrList.indexOf(item) === index;
})
9、Map对象是JavaScript提供的一种数据结构,结构为键值对形式,将数组元素作为map的键存入,前端培训然后结合has()和set()方法判断键是否重复。
// 9、利用new Map()
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
let newArrList = [];
let map = new Map();
arrList.forEach(item => {
if (!map.has(item)) {
newArrList.push(item);
map.set(item, true);
}
})
10、利用 reduce 结合 includes 去重
// 10、利用 reduce 结合 includes 去重
let arrList = [1, 1, 4, 2, 4, 3, 8, 4, 999, 5, 6, 7, 5];
let newArrList = arrList.reduce((prev, cur) => {
return prev.includes(cur) ? prev : [...prev, cur]
},[])
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。