翼度科技»论坛 编程开发 JavaScript 查看内容

JavaScript实现数组对象去重

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
有多种实现方式:
一、使用 Set 对象:
  1. Array.from(new Set(array))
复制代码
该方法会先创建一个 Set 对象,然后再使用 Array.from 方法将 Set 对象转换为数组,因为 Set 对象不允许有重复的元素,所以这样可以实现去重的效果。
但是,如果数组中的元素是对象,Set 对象会识别为不同的元素,所以不能直接使用该方法。为了解决这个问题,你可以使用一个映射函数,将数组中的对象映射为一个字符串或数字,然后再使用该方法。
以下是一个具体的例子:
  1. const arr = [
  2.     { id: 1, name: 'A' },
  3.     { id: 2, name: 'B' },
  4.     { id: 1, name: 'A' },
  5.     { id: 3, name: 'C' }
  6. ];
  7. const result = Array.from(new Set(arr.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
  8. console.log(result);
复制代码
 
二、使用`reduce`方法:
  1. const arr = [
  2.     { id: 1, name: 'A' },
  3.     { id: 2, name: 'B' },
  4.     { id: 1, name: 'A' },
  5.     { id: 3, name: 'C' }
  6. ];
  7. const result = arr.reduce((pre, cur) => {
  8.     var exists = pre.find(item => JSON.stringify(item) === JSON.stringify(cur));
  9.     if (!exists) {
  10.         pre.push(cur);
  11.     }
  12.     return pre;
  13. }, []);
  14. console.log(result);
复制代码
 
三、使用`filter`方法
  1. const arr = [
  2.     { id: 1, name: 'A' },
  3.     { id: 2, name: 'B' },
  4.     { id: 1, name: 'A' },
  5.     { id: 3, name: 'C' }
  6. ];
  7. const result =arr.filter((item, index, self) => {
  8.     return self.findIndex(t => JSON.stringify(t) === JSON.stringify(item)) === index;
  9. });
  10. console.log(result);
复制代码
 

来源:https://www.cnblogs.com/lyso/p/17106852.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具