js数组去重有哪些方法?
时间: 2023-07-06 16:36:29 浏览: 116
JavaScript数组去重的方法有以下几种:
1. 使用Set数据结构(ES6):Set是ES6中的新数据结构,可以自动去重。将数组转为Set,再将Set转回数组即可。
```
let arr = [1, 2, 3, 2, 1];
let newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3]
```
2. 使用indexOf方法:遍历原数组,将每个元素与新数组进行比较,如果新数组中不存在该元素,则将其添加到新数组中。
```
let arr = [1, 2, 3, 2, 1];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i]);
}
}
console.log(newArr); // [1, 2, 3]
```
3. 使用includes方法(ES7):与indexOf方法类似,includes方法也可以判断一个元素是否存在于数组中。
```
let arr = [1, 2, 3, 2, 1];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (!newArr.includes(arr[i])) {
newArr.push(arr[i]);
}
}
console.log(newArr); // [1, 2, 3]
```
4. 使用filter方法:使用filter方法过滤掉重复元素。
```
let arr = [1, 2, 3, 2, 1];
let newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(newArr); // [1, 2, 3]
```
5. 使用reduce方法:使用reduce方法合并数组,同时去除重复元素。
```
let arr = [1, 2, 3, 2, 1];
let newArr = arr.reduce((prev, cur) => {
if (prev.indexOf(cur) === -1) {
prev.push(cur);
}
return prev;
}, []);
console.log(newArr); // [1, 2, 3]
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)