用JS写数组去重的几种方法
时间: 2023-05-26 14:02:51 浏览: 95
1. 使用Set:
```javascript
const arr = [1, 1, 2, 3, 3, 4, 4, 5];
const result = [...new Set(arr)];
console.log(result); // [1, 2, 3, 4, 5]
```
2. 使用reduce:
```javascript
const arr = [1, 1, 2, 3, 3, 4, 4, 5];
const result = arr.reduce((unique, item) => {
return unique.includes(item) ? unique : [...unique, item];
}, []);
console.log(result); // [1, 2, 3, 4, 5]
```
3. 使用filter和indexOf:
```javascript
const arr = [1, 1, 2, 3, 3, 4, 4, 5];
const result = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(result); // [1, 2, 3, 4, 5]
```
4. 使用对象属性去重:
```javascript
const arr = [1, 1, 2, 3, 3, 4, 4, 5];
const obj = {};
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (obj[item]) {
continue;
} else {
obj[item] = true;
}
}
const result = Object.keys(obj).map(item => Number(item));
console.log(result); // [1, 2, 3, 4, 5]
```
阅读全文