方法一 … new Set
let test=[1,2,1,2,3,5,4,8,6,1];
[...new Set(test)]
//[1, 2, 3, 5, 4, 8, 6]
方法二 Array.from +new Set
let test=[1,2,1,2,3,5,4,8,6,1];
Array.from(new Set(test))
//(7) [1, 2, 3, 5, 4, 8, 6]
方法三 Map.has 存在true
let test=[1,2,1,2,3,5,4,8,6,1];
function unique(arr) {
const res = new Map();
return arr.filter((a) => !res.has(a) && res.set(a, 1))
};
unique(test)
//(7) [1, 2, 3, 5, 4, 8, 6]
方法四 es5 循环便利
- 创建一个新的空数组,用来存放去重后的新数组.
- 利用for循环循环遍历需要去重的数组.
- 利用indexOf()方法查询遍历出的数组在新数组中是否出现,如果出现:则继续遍历数组,如未出现:则利用push方法添加到新数组中.
- 原数组循环遍历完成后,组建一个已经去除重复的新数组.
转自:https://www.cnblogs.com/myprogramer/p/12107575.html