js数组去重

JS数组

let mixedArray = [
  'string',        // 字符串
  123,             // 数字
  true,            // 布尔值
  { key: 'value' }, // 对象
  null,            // 空值
  [1, 2, 3],       // 嵌套数组
  function() {} ,   // 函数
  undefined,
  'string',        // 字符串
  123,             // 数字
  true,            // 布尔值
  { key: 'value' }, // 对象
  null,            // 空值
  [1, 2, 3],       // 嵌套数组
  function() {} ,   // 函数
  undefined,
];
使用Set去重
let arr1 =Array.from(new Set(mixedArray)) 
console.log(arr1);
得到结果:
[
  "string",
  123,
  true,
  {
    key: "value",
  },
  null,
  [1, 2, 3],
  function () {},
  undefined,
  {
    key: "value",
  },
  [1, 2, 3],
  function () {},
];

可见使用Set直接去重,对于基本数据类型起作用,引用不起作用
filter和indexOf配合使用
indexOf() 方法返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。
findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。
let arr2 = mixedArray.filter((item, index) => mixedArray.indexOf(item) === index);
console.log(arr2,'arr2')
得到结果:
[
  "string",
  123,
  true,
  {
    key: "value",
  },
  null,
  [1, 2, 3],
  function () {},
  undefined,
  {
    key: "value",
  },
  [1, 2, 3],
  function () {},
];
对象数组去重
const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}];
const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值