js中 查找 数组中对象去重
时间: 2023-12-03 22:21:08 浏览: 34
你可以使用 Set 数据结构来进行数组中对象的去重。具体实现如下:
```javascript
const arr = [{id: 1, name: 'Tom'}, {id: 2, name: 'Jerry'}, {id: 1, name: 'Tom'}];
const set = new Set(arr.map(JSON.stringify));
const uniqueArr = Array.from(set).map(JSON.parse);
console.log(uniqueArr); // 输出 [{id: 1, name: 'Tom'}, {id: 2, name: 'Jerry'}]
```
这里使用了 map 方法将数组中的每个对象转换为字符串,再使用 Set 去重,最后再将字符串转换为对象。这样做的关键在于 Set 数据结构只会存储唯一的值。
相关问题
js去重数组中对象相同的值
在JavaScript中,可以使用reduce()和findIndex()方法来去除数组中对象相同的值。首先,通过reduce()方法遍历整个数组,将每个对象的属性值合并为一个字符串,然后使用findIndex()方法在新数组中查找是否已经存在相同字符串。如果没有找到,则将该字符串添加到新数组中,否则忽略该对象。
以下是一个示例代码:
```
const arr = [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 1, name: 'apple' }];
const result = arr.reduce((acc, cur) => {
const stringified = JSON.stringify(cur); // 将对象转换为字符串
const exists = acc.findIndex(item => JSON.stringify(item) === stringified); // 判断是否已存在
if (exists === -1) {
acc.push(cur);
}
return acc;
}, []);
console.log(result); // [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }]
```
在上面的代码中,我们使用JSON.stringify()将每个对象转换为字符串,以便后续比较。然后使用findIndex()方法,在新数组中查找是否已包含相同的字符串。如果已经存在相同的字符串,则返回该元素所在的位置,否则返回-1。最后,如果该元素不存在,则将其添加到新数组中。最后,返回新数组即可。
该方法可以很好地去除数组中对象相同的值,并返回一个去重后的新数组。
js中数组对象去重filter
在 JavaScript 中,你可以使用 `filter` 方法来对数组进行去重操作。下面是一个示例代码:
```javascript
const array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 3, name: 'Bob' },];
const uniqueArray = array.filter((obj, index, self) =>
index === self.findIndex((o) => o.id === obj.id && o.name === obj.name)
);
console.log(uniqueArray);
```
上述代码中,我们使用 `filter` 方法和 `findIndex` 方法来进行去重操作。`filter` 方法接受一个回调函数,该函数会在数组的每个元素上被调用。在回调函数中,我们使用 `findIndex` 方法来查找当前元素在数组中的第一个索引位置。如果当前元素的索引与其第一次出现的索引位置相同,则保留该元素,否则过滤掉重复元素。
在上面的示例中,最终会输出如下结果:
```javascript
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
]
```
注意:此方法对于数组中的对象元素的属性进行一一比较,如果对象属性较多或者属性值较复杂,建议使用其他更适合的去重方式。