js写一个数组对象去重
时间: 2023-05-17 14:07:19 浏览: 65
var arr = [{name: 'Tom', age: 18}, {name: 'John', age: 20}, {name: 'Tom', age: 18}];
var result = arr.reduce(function (unique, item) {
var key = item.name + '_' + item.age;
if (!unique[key]) {
unique[key] = item;
}
return unique;
}, {});
var newArr = Object.values(result);
console.log(newArr);
相关问题
用js写一个数组对象去重方法
以下是一种常见的去重方法:
```javascript
function unique(arr) {
var obj = {};
var result = [];
for (var i = 0; i < arr.length; i++) {
if (!obj[arr[i]]) {
obj[arr[i]] = true;
result.push(arr[i]);
}
}
return result;
}
```
使用方式:
```javascript
var arr = [1, 1, 2, 3, 3, 3, 4, 5, 5];
var result = unique(arr);
console.log(result); // [1, 2, 3, 4, 5]
```
该方法使用一个对象来记录数组中出现过的元素,遇到重复元素就跳过,最后返回去重后的结果数组。
js一个数组对象去重
你可以使用以下几种方法来对一个数组对象进行去重:
1. 使用 Set 数据结构:将数组转换为 Set,然后再将 Set 转换回数组。由于 Set 的特性是不允许重复值,所以会自动重。
```javascript
const array = [{id: 1}, {id: 2 {id: 1}];
const uniqueArray = Array.from(new Set(array.map(JSON.stringify)),.parse);
console.log(uniqueArray);
```
2. 使用 reduce 方法:使用 reduce 方法遍历数组,将每个对象的某个属性作为键,存储到一个空对象中,最后获取对象的值转换为数组。
```javascript
const array = [{id: 1}, {id: 2}, {id: 1}];
const uniqueArray = Object.values(array.reduce((acc, obj) => {
acc[obj.id] = obj;
return acc;
}, {}));
console.log(uniqueArray);
```
3. 使用 filter 方法:使用 filter 方法遍历数组,通过判断某个属性在新数组中是否已存在来进行去重。
```javascript
const array = [{id: 1}, {id: 2}, {id: 1}];
const uniqueArray = array.filter((obj, index, self) =>
index === self.findIndex((o) => o.id === obj.id)
);
console.log(uniqueArray);
```
以上是几种常见的数组对象去重方法,你可以根据具体的需求选择适合的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)