js数组对象或数组去重

for (let i = 0; i < arr.length - 1; i++) {
 for (let j = i + 1; j < arr.length; j++) {
    if (arr[i] === arr[j]) {
      arr.splice(j, 1) // 因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
      j--
  }
}

补充
如果要比较对象中的值是否相等,可以使用 lodash/isEqual方法,可以比较对象嵌套深层的内容

import isEqual from 'lodash/isEqual'
let object = { a: 1, c: { d: 1 } }
let other = { a: 1, c: { d: 1 } }

isEqual(object, other)
// => true

数组对象去重

  import { isEqual, uniqWith, uniqBy } from 'lodash'
  let arr = [
  {id: 1, name: 'xx', year: 18},
  {id: 2, name: 'xxx', year: 19},
  {id: 1, name: 'xxx', year: 20},
  {id: 3, name: 'xx', year: 21},
  {id: 3, name: 'xx', year: 18},
]
console.log('原数组:', arr);
console.log('根据id去掉相同的元素:', uniqBy(arr, 'id'));
console.log('检查数组每一项进行去重:', uniqWith(arr, isEqual));

数组去重

在JavaScript中,有多种方法可以对数组进行去重。以下是几种常用的方法:

使用Set:Set是ES6中引入的新的数据结构,它可以存储唯一的值。通过将数组转换为Set,然后再将Set转换回数组,就可以实现去重。

const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3, 4, 5]

使用filter方法和indexOf:遍历数组,通过判断元素在数组中的索引位置,来去掉重复的元素。

const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.filter((item, index) => {
  return arr.indexOf(item) === index;
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]

使用reduce方法:遍历数组,将元素添加到一个新数组中,在添加之前检查新数组中是否已存在相同的元素。

const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.reduce((acc, curr) => {
  if (!acc.includes(curr)) {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

使用Map:遍历数组,将元素作为Map的键,判断键是否存在于Map中,如果不存在则添加到新数组中。

const arr = [1, 2, 3, 3, 4, 4, 5];
const map = new Map();
const uniqueArr = [];
arr.forEach(item => {
  if (!map.has(item)) {
    map.set(item, true);
    uniqueArr.push(item);
  }
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值