JS数组去重
时间: 2023-06-21 08:10:17 浏览: 118
JS数组去重有多种方法,下面介绍其中两种常用的方法:
1. 使用Set
使用Set的特性,可以很方便地去掉数组中的重复元素。具体实现代码如下:
```javascript
const arr = [1, 2, 3, 2, 1];
const result = [...new Set(arr)];
console.log(result); // [1, 2, 3]
```
2. 使用filter和indexOf
通过遍历数组,使用indexOf判断元素是否已经存在于新数组中,如果不存在则添加到新数组中,最后返回新数组。具体实现代码如下:
```javascript
const arr = [1, 2, 3, 2, 1];
const result = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(result); // [1, 2, 3]
```
这两种方法都可以实现数组去重,选择哪种方法取决于具体情况。如果需要保持原数组的顺序,则应该选择第二种方法;如果不需要保持原数组的顺序,则可以选择第一种方法,因为Set会自动去重并保持顺序。
相关问题
js数组去重set方法
JavaScript中可以使用Set对象来实现数组去重。Set对象是一种集合数据结构,其中的元素唯一,不会重复。可以将一个数组转换为Set对象,然后再将Set对象转换为数组,就可以得到去重后的数组。
下面是使用Set方法实现数组去重的示例代码:
```
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
```
在上面的代码中,首先定义了一个包含重复元素的数组arr。然后使用Set对象去重,通过`[...new Set(arr)]`将Set对象转换为数组uniqueArr,最后输出结果。
javascript数组去重
以下是两种JavaScript数组去重的方法:
1. 使用indexOf方法进行数组去重
```javascript
function uniqArr(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
}
```
2. 使用Set数据结构进行数组去重(ES6)
```javascript
function uniqArr(arr) {
return Array.from(new Set(arr));
}
```
阅读全文
相关推荐
![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)
![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://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](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)