数组对象去重js
时间: 2023-06-21 20:10:22 浏览: 48
可以使用 Set 数据结构来去重数组对象,然后将 Set 转换回数组即可。
例如:
```javascript
const arr = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 1, name: "John" },
{ id: 3, name: "Sarah" },
];
const uniqueArr = Array.from(new Set(arr.map((item) => item.id))).map((id) =>
arr.find((item) => item.id === id)
);
console.log(uniqueArr);
```
这段代码首先使用 `map` 方法将原数组中的每个对象转换为它们的 `id` 值,并用 `Set` 去重。然后通过 `Array.from` 将 `Set` 转换为数组,再使用 `map` 方法找到原数组中对应的对象,最终返回的就是去重后的数组对象。
相关问题
js数组对象去重的方法
JavaScript中数组对象去重的方法有很多种,下面列举几种常见的方法:
1. 使用Set:使用Set数据结构可以快速实现数组对象的去重。通过将数组对象转化为Set,再将Set转化回数组即可实现去重。
```javascript
const arr = [{id: 1}, {id: 2}, {id: 1}, {id: 3}];
const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr);
```
2. 使用reduce方法:利用reduce方法遍历数组对象,通过判断对象在结果数组中是否已存在来进行去重。
```javascript
const arr = [{id: 1}, {id: 2}, {id: 1}, {id: 3}];
const uniqueArr = arr.reduce((result, current) => {
const isExist = result.some(item => item.id === current.id);
if (!isExist) {
result.push(current);
}
return result;
}, []);
console.log(uniqueArr);
```
3. 使用filter方法:利用filter方法和indexOf来判断对象在数组中的索引位置,从而进行去重。
```javascript
const arr = [{id: 1}, {id: 2}, {id: 1}, {id: 3}];
const uniqueArr = arr.filter((item, index, self) => {
return index === self.findIndex(obj => obj.id === item.id);
});
console.log(uniqueArr);
```
以上是一些常见的数组对象去重方法,根据具体业务场景选择适合的方法即可。
js数组对象去重
可以使用 Set 数据结构来实现数组对象去重。具体实现如下:
```javascript
const arr = [
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Jerry' },
{ id: 1, name: 'Tom' },
{ id: 3, name: 'Lucy' }
];
const set = new Set(arr.map(JSON.stringify));
const newArr = Array.from(set).map(JSON.parse);
console.log(newArr);
// Output: [{ id: 1, name: 'Tom' }, { id: 2, name: 'Jerry' }, { id: 3, name: 'Lucy' }]
```
上述代码中,先使用 `map` 方法将每个对象转换为字符串形式,然后将其作为 Set 的元素,这样就可以去重了。最后再将 Set 转换为数组,并使用 `map` 方法将字符串转换为对象形式即可得到去重后的数组。