js数组去重有哪些方法
时间: 2023-10-12 22:16:10 浏览: 84
1. 使用 Set 去重:
```
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3, 4, 5]
```
2. 使用 filter 去重:
```
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(newArr); // [1, 2, 3, 4, 5]
```
3. 使用 reduce 去重:
```
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = arr.reduce((prev, cur) => {
if (prev.indexOf(cur) === -1) {
prev.push(cur);
}
return prev;
}, []);
console.log(newArr); // [1, 2, 3, 4, 5]
```
4. 使用 for 循环和 indexOf 去重:
```
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i]);
}
}
console.log(newArr); // [1, 2, 3, 4, 5]
```
5. 使用 ES6 的 includes 去重:
```
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (!newArr.includes(arr[i])) {
newArr.push(arr[i]);
}
}
console.log(newArr); // [1, 2, 3, 4, 5]
```
阅读全文