数组去重
时间: 2023-06-21 21:06:38 浏览: 31
数组去重有多种方法,以下是其中几种:
1. 使用 Set 数据结构
```javascript
const arr = [1, 2, 2, 3, 3, 4];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4]
```
2. 使用 filter 方法
```javascript
const arr = [1, 2, 2, 3, 3, 4];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // [1, 2, 3, 4]
```
3. 使用 reduce 方法
```javascript
const arr = [1, 2, 2, 3, 3, 4];
const uniqueArr = arr.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], []);
console.log(uniqueArr); // [1, 2, 3, 4]
```
以上是几种比较常见的数组去重方法,可以根据实际需求选择适合的方法。
相关问题
Javascript数组去重
以下是三种Javascript数组去重的方法:
1.使用Set方法进行数组去重
```javascript
const arr = [1, 2, 3, 3, 4, 4, 5];
const newArr = [...new Set(arr)];
console.log(newArr); // 输出:[1, 2, 3, 4, 5]
```
2.使用filter方法进行数组去重
```javascript
const arr = [1, 2, 3, 3, 4, 4, 5];
const newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(newArr); // 输出:[1, 2, 3, 4, 5]
```
3.使用reduce方法进行数组去重
```javascript
const arr = [1, 2, 3, 3, 4, 4, 5];
const newArr = arr.reduce((prev, cur) => {
if (prev.indexOf(cur) === -1) {
prev.push(cur);
}
return prev;
}, []);
console.log(newArr); // 输出:[1, 2, 3, 4, 5]
```
react 数组去重
React 是一个 JavaScript 库,主要用于构建用户界面。React 本身并没有提供数组去重的功能,但是可以利用 JavaScript 中的 Set 来实现数组去重。
Set 是 ES6 中新增的一种数据结构,它类似于数组,但是成员的值都是唯一的,没有重复的值。因此,可以使用 Set 来实现数组去重。
以下是使用 Set 实现数组去重的代码示例:
```
const arr = [1, 2, 3, 1, 2, 4];
const newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3, 4]
```
这里先使用 Set 对数组进行去重,然后再使用 Array.from 将 Set 转换为数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)