项目中积累的javaScript数组去重超级好用方法

 

1.Es6的Set数组去重法:(ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。)

let aList = [1, 2, 5, 6, 4, 9, 2, 1, 2, 3, 4, 5, 6, 5, 5, 3, 3, 4, 2, 1];
let aList2 = [...new Set(aList)];
console.log(aList2); //1,2,5,6,4,9,3
2.遍历,将值添加到新数组,用indexOf() (该方法是返回数组中元素第一次出现的索引值;如果有,则正常返回索引值;如果检索的内容不存在于数组中,则返回-1) 判断值是否存在,已存在就不添加,达到去重效果。
 let testArr = ['1', '2', '3', 1, NaN, NaN, undefined, undefined, null, null, 'a', 'b', 'b'];
        let newArray = [];
        for (let item of testArr) {
            if (newArray.indexOf(item) == -1) {
                newArray.push(item)
            } else {
                console.log('重复了', item)
            }
        }
        console.log(newArray); //["1", "2" , "3" , 1, NaN,NaN, undefined, null, "a", "b"]

3.遍历,将数组的值添加到一个对象的属性名里,并给属性赋值,对象不能添加相同属性名,以这个为依据可以实现数组去重,然后用Object.keys(对象)返回这个对象可枚举属性组成的数组,这个数组就是去重后的数组

 let A = ['1', '2', '3', 1, NaN, NaN, undefined, undefined, null, null, 'a', 'b', 'b'];
        const unique = arr => {
            let obj = {}
            arr.forEach(value => {
                obj[value] = 0; //这步新添加一个属性,并赋值,如果不赋值的话,属性会添加不上去
            })
            return Object.keys(obj); //`Object.keys(对象)`返回这个对象可枚举属性组成的数组,这个数组就是去重后的数组
        }
        console.log(unique(a)); //["1", "2", "3", "NaN", "undefined", "null", "a", "b"]

4.相比较filter(),forEach()还有一些遍历去实现的方法来说这个方法很简单,是超级好用的js数组去重

 let array = [{
                id: 1,
                value: 1
            }, {
                id: 2,
                value: 2
            }, {
                id: 3,
                value: 2
            }, {
                id: 4,
                value: 3
            }, {
                id: 5,
                value: 4
            }];
            let obj = {};
            array = array.reduce((cur, next) => {
                obj[next.value] ? "" : obj[next.value] = true && cur.push(next);
                return cur;
            }, []);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值