数组去重的三种方法
第一种使用 new set方法
new set 是最简单的一种方法了
具体代码如下:
/* 1. 使用 new set 去重 Array.from转化成数组 */
const arr = [1, 2, 3, 5, 6, 3, 10, 5];
// const array = Array.from(new Set(arr));
/* ... 是展开运算符 */
const array = [...new Set(arr)]
console.log(array);
第二种使用循环来去重
我把它分为四部
1.首先创建一个空的数组
2.使用 forEach 循环数组中的每一项
3. 在用 indexOf 判断数组里面有没有 item 没有返回的就是-1 有返回的就是 1
4. 然后直接push进去
具体代码如下:
/* 2. 使用循环来去重 */
const arr = [1, 2, 3, 5, 6, 3, 10, 5];
// 1.首先创建一个空的数组
const result = []
// 2.使用 forEach 循环数组中的每一项
arr.forEach(item=>{
// 3. 在用 indexOf 判断数组里面有没有 item 没有返回的就是-1 有返回的就是 1
if(result.indexOf(item) === -1){
// 4.然后直接push进去
result.push(item)
}
})
console.log(result);
第三种方法使用对象
- 定义一个空的对象 , 空的数组
- 遍历这个数组 在数组里判断 这个对象里面的key 有没有数组里面的元素 如果没有就给他一个初始值 如果有就++
- 循环这个对象 循环对象用 fo in 判断这个对象的 val 等不等一 等于一 就添加到数组里
const arr = [1, 2, 3, 5, 6, 3, 10, 5];
// 1 定义一个空的对象 , 空的数组
let obj = {}
let result = []
// 2 遍历这个数组 在数组里判断 这个对象里面的key 有没有数组里面的元素 如果没有就给他一个初始值 如果有就++
arr.forEach(item=>{
if(!obj[item]){
obj[item]=1
}else{
obj[item]++
}
})
// 3 循环这个对象 循环对象用 fo in 判断这个对象的 val 等不等一 等于一 就添加到数组里
for (const key in obj) {
if(obj[key] === 1){
// +号是吧字符串转换成数字
result.push(+key)
}
}
console.log(obj)
console.log(result)
这三种是本人自己总结的哈 不足地方多多指教留言