数组去重
forEach
调用数组的每个元素,并将元素传递给回调函数。
let arr = [1, 2, 1, 3, 2, 3, 4, 5, 6, 5]
let arrRes = []
arr.forEach((item)=>{
arrRes.indexOf(item) === -1 && arrRes.push(item)
})
console.log(arrRes)
// [1, 2, 3, 4, 5, 6]
1
2
3
4
5
6
7
2
3
4
5
6
7
Set对象 & from方法
Set 对象允许你存储任何类型的
唯一值,无论是原始值或者是对象引用。并返回一个新的set对象。
from方法从一个类似数组或可迭代对象中创建一个新的
数组实例。
let arr = [1, 2, 1, 3, 2, 3, 4, 5, 6, 5]
let arrRes = Array.from(new Set(arr))
console.log(arrRes)
// [1, 2, 3, 4, 5, 6]
1
2
3
4
2
3
4
或者也可以这样
const unique = arr => [...new Set(arr)];
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
1
2
2
去重的同时去除数组中 无效值 可以用
const unique = arr => [...new Set(arr.filter(x=>x))];
// unique([1,2,2,3,4,4,,undefined,NaN]) -> [1,2,3,4]
1
2
2
← 数组排序 两个数组取相同、不同项 →