js处理数组某个字段去重的方法
时间: 2024-05-12 13:20:51 浏览: 37
JavaScript数组去重的几种方法
1. 使用Set数据结构
```javascript
const arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'apple'}, {id: 4, name: 'orange'}];
const uniqueNames = [...new Set(arr.map(item => item.name))];
console.log(uniqueNames); // ['apple', 'banana', 'orange']
```
2. 使用reduce方法
```javascript
const arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'apple'}, {id: 4, name: 'orange'}];
const uniqueNames = arr.reduce((acc, cur) => {
if (!acc.includes(cur.name)) {
acc.push(cur.name);
}
return acc;
}, []);
console.log(uniqueNames); // ['apple', 'banana', 'orange']
```
3. 使用filter方法
```javascript
const arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'apple'}, {id: 4, name: 'orange'}];
const uniqueNames = arr.filter((item, index, array) => {
return array.findIndex(i => i.name === item.name) === index;
}).map(item => item.name);
console.log(uniqueNames); // ['apple', 'banana', 'orange']
```
4. 使用forEach方法
```javascript
const arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'apple'}, {id: 4, name: 'orange'}];
const uniqueNames = [];
arr.forEach(item => {
if (!uniqueNames.includes(item.name)) {
uniqueNames.push(item.name);
}
});
console.log(uniqueNames); // ['apple', 'banana', 'orange']
```
阅读全文