对象去重

21 阅读2分钟

假设有一个数组 arr = [1, 2, 3, 1, 2, 4, 5, 3],我们需要将其中的重复元素去掉,得到一个新的数组。

方法一:使用 Set

Set 是 ES6 中新增的数据结构,它可以用来存储一组唯一的值。我们可以将原数组转换为 Set,然后再将 Set 转换回数组,这样就能去掉重复元素了。

```javascript
let arr = [1, 2, 3, 1, 2, 4, 5, 3];
let newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3, 4, 5]
```

方法二:使用 filter

我们可以遍历原数组,使用 filter 方法过滤掉重复元素。具体做法是,对于原数组中的每个元素,我们判断它是否在数组中的索引位置和当前位置相等,如果相等,则说明它是第一次出现,否则就是重复元素,应该被过滤掉。

```javascript
let arr = [1, 2, 3, 1, 2, 4, 5, 3];
let newArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(newArr); // [1, 2, 3, 4, 5]
```

方法三:使用 reduce

我们可以使用 reduce 方法,将重复元素从原数组中剔除。具体做法是,对于原数组中的每个元素,我们判断它是否已经出现过,如果没有出现过,则将它添加到结果数组中,否则不做处理。

```javascript
let arr = [1, 2, 3, 1, 2, 4, 5, 3];
let newArr = arr.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], []);
console.log(newArr); // [1, 2, 3, 4, 5]
```

以上三种方法都可以实现数组去重,具体使用哪种方法取决于个人偏好和实际情况。

以下是一个js对象去重的示例:

```javascript
const arr = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 1, name: "John" },
  { id: 3, name: "Bob" },
  { id: 2, name: "Jane" }
];

const uniqueArr = Array.from(new Set(arr.map(a => a.id)))
  .map(id => {
    return arr.find(a => a.id === id)
  })

console.log(uniqueArr);
// Output: [{ id: 1, name: "John" }, { id: 2, name: "Jane" }, { id: 3, name: "Bob" }]
```

在上面的示例中,我们首先使用`map()`方法将原始数组中每个对象的`id`属性提取出来,并使用`new Set()`方法将其转换为一个唯一的集合。然后,我们使用`map()`方法遍历唯一的`id`集合,并使用`find()`方法找到第一个具有相应`id`属性的原始对象。最后,我们将这些对象组合成一个新的数组,并将其存储在`uniqueArr`变量中。