js数组去重
2022-01-11 本文已影响0人
Astep
面试常问数组去重方法有那些:
1.用Es6的Set方法
Array.from(new Set(arr)); 或 [...new Set(arr)]
2.使用双重for循环,再利用数组的splice方法去重(ES5常用)
let arr = [1, 3, 4, 2, 7, 5, 9, 0, 5, 3, 5, 8, 2, 3, 4, 7, 5, 2, 1, 0];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
j--;
}
}
}
3.利用数组的includes去重
let arr = [1,3,4,2,7,5,9,0,5,3,5,8,2,3,4,7,5,2,1,0];
let result = [];
arr.forEach((currentValue)=>{
if(!result.includes(currentValue)){
result.push(currentValue);
}
});
4.利用对象的key不能重复去重
let arr = [1,3,4,2,7,5,9,0,5,3,5,8,2,3,4,7,5,2,1,0];
let obj ={};
for(let i = 0;i<arr.length;i++){
obj[arr[i]] = true;
}
const result = Object.keys(obj);
5.使用数组的filter和indexOf方法去重 (利用indexOf原理,总是找到出现第一次元素的位置就返回)
let arr = [1,3,4,2,7,5,9,0,5,3,5,8,2,3,4,7,5,2,1,0];
const result = arr.filter((currentValue,ind,self)=>{
return self.indexOf(currentValue)===ind;
});
6.利用ES6中的Map方法去重
let arr = [1,3,4,2,7,5,9,0,5,3,5,8,2,3,4,7,5,2,1,0];
let map1 = new Map();
arr.forEach((item)=>{
if(!map1.has(item)) map1.set(item,true);
});
let reslut = Array.from(map1.keys());