js 数组对象如何去重
时间: 2024-06-17 14:06:44 浏览: 58
JavaScript中可以使用Set对象来实现数组去重。Set是一种集合,其中不会出现重复的元素。我们可以将数组转换为Set,然后再将Set转换回数组即可。
以下是示例代码:
```javascript
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3, 4, 5]
```
在这里,我们首先使用new Set(arr)将数组转换为Set,然后使用Array.from()将Set转换为数组。这样就得到了一个去重后的数组。
相关问题
写一段js数组对象去重
可以使用 ES6 中的 Set 构造函数,具体实现代码如下:
let arr = [{id: 1}, {id: 2}, {id: 1}];
let newArr = Array.from(new Set(arr.map(item => item.id))).map(id => {
return arr.find(item => item.id === id);
});
js数组对象去重方法
JavaScript中有多种方法可以对数组进行去重操作,以下是其中的一些常见方法:
1. **Set** 对象:Set是一个特殊的内置对象,它只允许存储唯一的值(包括原始值和Object)。你可以将数组转换成Set,然后再转回数组,即可实现去重。
```javascript
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
```
2. **filter() + includes()**:通过遍历数组,检查每个元素是否不在新的数组中,实现去重。
```javascript
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = arr.filter((item, index, self) => {
return self.indexOf(item) === index;
});
```
3. **reduce()**:利用reduce方法将数组变为单个值,并基于已存在的值决定元素是否应添加到结果数组。
```javascript
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = arr.reduce((prev, curr) => prev.includes(curr) ? prev : [...prev, curr], []);
```
4. **双重循环**:简单的双层for循环,外层遍历数组,内层判断当前元素是否已经存在于新数组中。
```javascript
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [];
for (let i = 0; i < arr.length; i++) {
if (!uniqueArr.includes(arr[i])) {
uniqueArr.push(arr[i]);
}
}
```
阅读全文
相关推荐
![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)