array.filter((item, index) => array.indexOf(item) === index);
时间: 2024-05-22 15:14:41 浏览: 9
This code snippet filters an array to only include unique values. It accomplishes this by using the `filter()` method on the array and passing a callback function as an argument. The callback function takes two parameters: `item`, which represents the current element being processed, and `index`, which represents the index of the current element.
Inside the callback function, the `indexOf()` method is used to check if the current item is the first occurrence of that element in the array. If it is, then the `indexOf()` method will return the current index of the element, which will match the `index` parameter passed to the callback function. If it is not the first occurrence, then the `indexOf()` method will return the index of the first occurrence of that element, which will not match the `index` parameter.
By comparing the return value of `indexOf()` with the `index` parameter, we can determine if the current item is unique or not. If it is, then the callback function returns `true`, which includes the item in the filtered array. If it is not unique, then the callback function returns `false`, which excludes the item from the filtered array.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)