js filter数组对象去重
时间: 2023-08-24 22:07:19 浏览: 45
你可以使用`filter`方法和`indexOf`来过滤数组对象中的重复项。具体步骤如下:
1. 使用`filter`方法迭代数组对象。
2. 在`filter`的回调函数中,使用`indexOf`方法检查当前项在数组中的索引位置。
3. 如果当前项的索引与`indexOf`的返回值相同,则表示当前项是第一次出现,保留该项。
4. 最后返回过滤后的数组。
以下是一个示例代码:
```javascript
let arr = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 1, name: 'Apple' },
{ id: 3, name: 'Orange' }
];
let uniqueArr = arr.filter((item, index) => {
return arr.findIndex(obj => obj.id === item.id) === index;
});
console.log(uniqueArr);
```
输出结果为:
```
[
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
```
这样就实现了对数组对象的去重。希望能对你有所帮助!如果有任何问题,请随时问我。
相关问题
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' },
]
```
注意:此方法对于数组中的对象元素的属性进行一一比较,如果对象属性较多或者属性值较复杂,建议使用其他更适合的去重方式。
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);
```
以上是一些常见的数组对象去重方法,根据具体业务场景选择适合的方法即可。