Open zxdfe opened 1 year ago
双重for循环去重
const arr = [1,2,3,4,6,2,3,4,1,5,6,8]
const newArr = []
for(let i = 0;i < arr.length;i++) {
for(let j = i + 1; j< arr.length - i;j++) {
if(arr[i] === arr[j]) {
arr.splice(j,1)
}
}
}
console.log(arr)
利用filter和indexOf实现去重
const arr = [1,2,3,4,6,2,3,4,1,5,6,8]
const newArr = arr.filter((el,index) => {
// 查找el第一次出现的位置,如果有下标与当前下标相同,则说明这是只出现过一次的元素,保留下来
return arr.indexOf(el) === index
})
console.log(newArr)
利用es6新增的set数据结构去重
// es6新增数据结构set,set对象可以存储任何类型的唯一值.
const arr = [1,2,3,4,6,2,3,4,1,5,6,8]
// 再将set转为数组,就实现了去重
const newArr = Array.from(new Set(arr))
console.log(newArr)
const arr = [1, 5, 9, 6, 1, 7, 3, 5, 6, 7]