利用数组中的filter方法,将已知数组var arr = ['apple','banana','pear','apple','orange','orange']; 去重
时间: 2023-09-02 07:07:43 浏览: 78
好的,那我来具体讲解一下这种方法的实现步骤:
1. 使用filter()方法遍历原数组arr,返回一个新数组,新数组中的元素满足以下条件:
- 在原数组中的下标等于该元素第一次出现的下标。
2. 返回新数组result即为去重后的数组。
代码实现如下:
```
function unique(arr) {
let result = arr.filter((item, index, self) => {
return self.indexOf(item) === index;
});
return result;
}
let arr = ['apple', 'banana', 'pear', 'apple', 'orange', 'orange'];
let result = unique(arr);
console.log(result); // ['apple', 'banana', 'pear', 'orange']
```
需要注意的是,这种方法的时间复杂度也比较高,为O(n^2),不适合处理大规模的数组。此外,使用indexOf()方法还有一个问题就是它无法去重NaN和{}等复杂数据类型。
相关问题
3) 利用数组中的filter方法,将已知数组var arr = ['apple','banana','pear','apple','orange','orange']; 去重
可以使用以下代码实现数组去重:
```
var arr = ['apple', 'banana', 'pear', 'apple', 'orange', 'orange'];
var uniqueArr = arr.filter(function(item, index, array) {
return array.indexOf(item) === index;
});
console.log(uniqueArr); // ['apple', 'banana', 'pear', 'orange']
```
这里使用了数组的 `filter` 方法,对数组中的每个元素进行过滤。在过滤的过程中,判断当前元素在数组中第一次出现的位置是否等于当前元素的位置,如果等于,则保留该元素,否则过滤掉该元素。这样就可以实现数组去重的目的。
var arr = new Array(2) 表示数组长度为2
是的,这行代码创建了一个长度为2的数组。但是需要注意的是,它创建的数组中并没有任何元素,即数组中的每个元素都是 undefined。如果想要创建并初始化数组,可以使用以下方式:
```
var arr = [1, 2]; // 创建并初始化一个长度为2的数组
```
或者:
```
var arr = new Array(1, 2); // 创建并初始化一个长度为2的数组
```
相关推荐
![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_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)