js数组去重6种方法
时间: 2023-09-23 18:06:39 浏览: 180
Sure! 下面是常见的6种JavaScript数组去重的方法:
1. 使用Set数据结构:Set是ES6引入的一种新的数据结构,它可以自动去除重复的值。
```javascript
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
```
2. 使用filter方法:使用filter方法遍历数组,然后通过indexOf判断当前元素在数组中的索引和当前索引是否相等,如果相等则保留,否则去除。
```javascript
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray);
```
3. 使用reduce方法:使用reduce方法遍历数组,将每个元素放入一个新数组中,同时使用includes方法判断新数组中是否已存在该元素。
```javascript
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = array.reduce((acc, currentValue) => {
if (!acc.includes(currentValue)) {
acc.push(currentValue);
}
return acc;
}, []);
console.log(uniqueArray);
```
4. 使用Map数据结构:使用Map数据结构可以根据键的唯一性去除重复值。
```javascript
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = Array.from(new Map(array.map(value => [value, value])).values());
console.log(uniqueArray);
```
5. 使用递归:使用递归来遍历数组,然后判断当前元素是否在之前的元素中出现过。
```javascript
const array = [1, 2, 3, 3, 4, 5, 5];
function unique(array) {
if (array.length === 1) {
return array;
}
if (array.slice(1).includes(array
阅读全文
相关推荐
















