合并数组并去重

1、利用Set的唯一特性,实现去重的目的(普通数组有效) 

let a = [1, 2, 3, 4];
let b = [2, 4];
let c = new Set([...b, ...a]); // Set对象的特性,成员的值是唯一的,从而达到去重的目的
let s = Array.from(c); // Array.from() 把Set对象在转化为数组
console.log('d',d); // [ 2, 4, 1, 3 ]

2、对象数组的去重

// 假设id为每一个元素的唯一确定项,针对相同的id去重
let arr = [
    { id: 1, text: 1 },
    { id: 2, text: 2 },
    { id: 3, text: 3 },
    { id: 1, text: 1 },
];

let arrMap = new Map();
arr.forEach(item => {
    arrMap.set(item.id, item);
})

let arrResult = [];
arrMap.forEach(item => {
    arrResult.push(item);
});

console.log('arrMap',arrMap); // arrMap Map {1 => { id: 1, text: 1 },2 => { id: 2, text: 2 },3 => { id: 3, text: 3 }}
console.log('arrResult',arrResult); // [ { id: 1, text: 1 }, { id: 2, text: 2 }, { id: 3, text: 3 } ]

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在JavaScript合并数组去重,有几种方法可以实现。以下是一些常用的方法: 方法1:使用Set对象 您可以使用Set对象来合并数组去重Set对象是一种集合,它只能存储唯一的值。您可以将数组转换为Set对象,然后将Set对象转换回数组,就可以实现合并去重。 示例代码: ``` let arr1 = [1, 2, 3, 4, 5]; let arr2 = [7, 8, 9, 4, 5]; let mergedArray = Array.from(new Set([...arr1, ...arr2])); console.log(mergedArray); ``` 这样,`mergedArray`将包含合并去重后的数组。 方法2:使用concat()方法 您也可以使用concat()方法来合并两个数组,并使用Set对象去重。concat()方法可用于连接两个或多个数组,并返回一个新的数组。 示例代码: ``` let arr1 = [1, 2, 3, 4, 5]; let arr2 = [7, 8, 9, 4, 5]; let mergedArray = Array.from(new Set(arr1.concat(arr2))); console.log(mergedArray); ``` 这样,`mergedArray`将包含合并去重后的数组。 方法3:使用forEach()方法 您还可以使用forEach()方法遍历一个数组,并将每个元素添加到另一个数组中。在添加之前,您可以使用includes()方法检查另一个数组是否已经包含该元素,以确保去重。 示例代码: ``` let arr1 = [1, 2, 3, 4, 5]; let arr2 = [7, 8, 9, 4, 5]; arr1.forEach(item => { if (!arr2.includes(item)) { arr2.push(item); } }); console.log(arr2); ``` 这样,`arr2`将包含合并去重后的数组。 以上是三种常见的JavaScript合并数组去重的方法。您可以根据您的实际需求选择合适的方法来解决问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值