JS 如何通过map函数去重
时间: 2024-04-08 17:11:40 浏览: 13
可以使用Set数据结构来去重,例如:
```
let arr = [2, 3, 2, 1, 4, 3];
let newArr = Array.from(new Set(arr));
console.log(newArr); // [2, 3, 1, 4]
```
也可以使用map函数和一个空的对象来实现去重,代码如下:
```
let arr = [2, 3, 2, 1, 4, 3];
let obj = {};
let newArr = arr.map(item => {
if (!obj[item]) {
obj[item] = true;
return item;
}
});
console.log(newArr.filter(item => item !== undefined)); // [2, 3, 1, 4]
```
以上两种方法都可以实现数组去重的功能。
相关问题
js数组对象set去重
可以使用 Set 对数组对象进行去重。具体实现方法如下:
```
let arr = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 1, name: 'Charlie'}];let set = new Set(arr.map(item => item.id));
let result = Array.from(set).map(id => arr.find(item => item.id === id));
```
上述代码中,首先使用 map() 函数遍历数组对象,将对象的 id 属性提取出来,然后使用 Set 对 id 数组进行去重。最后使用 map() 函数遍历去重后的 id 数组,通过 find() 函数找到对应的对象,最终得到一个去重后的新数组 result。
js 数组包对象去重
如果你的数组中包含对象,并且想要对这些对象进行去重操作,可以使用不同的方法。以下是一种常见的方法(使用JavaScript):
1. 使用集合(Set)和Array.from():集合是一种数据结构,可以确保其中的元素是唯一的。你可以使用`Set`来对数组中的对象进行去重。然后,将集合转换回数组,以得到去重后的结果。以下是一个示例:
```javascript
let array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' }, // 重复对象
{ id: 3, name: 'Alice' },
];
let uniqueArray = Array.from(new Set(array.map(JSON.stringify)), JSON.parse);
console.log(uniqueArray);
```
输出:
```
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Alice' }
]
```
在这个示例中,我们使用`map()`函数将数组中的对象转换为字符串,然后使用集合去除重复项,最后使用`JSON.parse`将字符串转回对象。
这种方法依赖于对象的字符串表示形式,因此对象的属性顺序可能会影响去重的结果。如果你需要根据对象的特定属性进行去重操作,请在`map()`函数中传入自定义的映射函数。
希望以上方法能对你有所帮助!