JavaScript数组,数组对象去重

数组去重

    let arr2 = ['小王', '小王', '小张']
    let newArr2 = [...new Set(arr2)]
    console.log("TCL: newArr2", newArr2) // TCL: newArr2 (2) ["小王", "小张"]

 

 

数组对象去重

1.reduce()方法

    let arr = [
        { name: 'wangqiang', age: 25 },
        { name: 'wangqiang1', age: 26 },
        { name: 'wangqiang1', age: 27 },
        { name: 'wangqiang2', age: 28 }
    ]
    let obj = {};
    let newArr = arr.reduce((defaultArr, next) => {
        obj[next.name] ? "" : obj[next.name] = true && defaultArr.push(next)
        return defaultArr
    }, [])
    //设置defaultArr默认类型为数组,并且初始值为空的数组
    console.log("TCL: newArr", newArr)
    // TCL: newArr
    // [
    //     { name: 'wangqiang', age: 25 },
    //     { name: 'wangqiang1', age: 26 },
    //     { name: 'wangqiang2', age: 28 }
    // ]

 2.冒泡排序的思想

    let arr1 = [
        { name: 'wangqiang', age: 25 },
        { name: 'wangqiang1', age: 26 },
        { name: 'wangqiang1', age: 27 },
        { name: 'wangqiang2', age: 28 }
    ]
    for (let i = 0; i < arr1.length - 1; i++) {
        for (let j = i + 1; j < arr1.length; j++) {
            if (arr1[j].name === arr1[i].name) {
                arr1.splice(j, 1)
            }
        }
    }
    console.log("TCL: arr1", arr1)
    // TCL: arr1
    // [
    //     { name: 'wangqiang', age: 25 },
    //     { name: 'wangqiang1', age: 26 },
    //     { name: 'wangqiang2', age: 28 }
    // ]

 

 

 

删除两个数组中name相同的对象

(项目需求  去掉已经选择的选项)

    let arr3 = [
        { name: 'wangqiang', age: 25 },
        { name: 'wangqiang1', age: 26 },
        { name: 'wangqiang2', age: 27 },
        { name: 'wangqiang3', age: 28 }
    ]
    let arr3_1 = [
        { name: 'wangqiang2', age: 28 }
    ]
    arr3 = arr3.filter(item => {
        let list = arr3_1.map(v => {
            return v.name
        })
        return !list.includes(item.name)
    })
    console.log("TCL: arr3", arr3)
    // TCL: arr3
    // [
    //     { name: 'wangqiang', age: 25 },
    //     { name: 'wangqiang1', age: 26 },
    //     { name: 'wangqiang3', age: 28 }
    // ]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值