用js写数组去重,用5中方法
时间: 2023-07-19 22:39:25 浏览: 91
1. 使用Set数据结构
```
const arr = [1, 2, 2, 3, 4, 4, 5];
const newArr = [...new Set(arr)];
console.log(newArr); // [1, 2, 3, 4, 5]
```
2. 使用for循环和indexOf方法
```
const arr = [1, 2, 2, 3, 4, 4, 5];
const 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]
```
3. 使用for循环和includes方法
```
const arr = [1, 2, 2, 3, 4, 4, 5];
const 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]
```
4. 使用filter方法
```
const arr = [1, 2, 2, 3, 4, 4, 5];
const newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(newArr); // [1, 2, 3, 4, 5]
```
5. 使用reduce方法
```
const arr = [1, 2, 2, 3, 4, 4, 5];
const newArr = arr.reduce((prev, curr) => {
if (!prev.includes(curr)) {
prev.push(curr);
}
return prev;
}, []);
console.log(newArr); // [1, 2, 3, 4, 5]
```
阅读全文