当前位置:网站首页>Object array de encapsulation

Object array de encapsulation

2022-06-13 08:41:00 Python's path to becoming a God

    /**
     *  Array object de duplication 
     * @param {Array} arr   An array of objects that need to be de duplicated 
     * @param {string} key  Identify duplicate keywords ,  If basic data type , No transmission 
     * */

    function arrNoRepeat(arr, key) {
        if(!key){
            return [...new Set(arr)]
        }
        let obj = {}
        arr = arr.reduce((item, next) => {
            obj[next[key]] ? '' : obj[next[key]] = true && item.push(next)
            return item
        }, [])
        return arr
    }

Test code ( The basic data type can also )

    /**
     *  Array object de duplication 
     * @param {Array} arr   An array of objects that need to be de duplicated 
     * @param {string} arr  Identify duplicate keywords ,  If basic data type , No transmission 
     * */

    function arrNoRepeat(arr, key) {
        if(!key){
            return [...new Set(arr)]
        }
        let obj = {}
        arr = arr.reduce((item, next) => {
            obj[next[key]] ? '' : obj[next[key]] = true && item.push(next)
            return item
        }, [])
        return arr
    }

    //  Arrays that need to be de duplicated 
    let myArr = [
        {
            id: 1,
            name: ' Xiao Ming '
        }, {
            id: 2,
            name: ' Xiaohong '
        }, {
            id: 1,
            name: ' Xiao Ming '
        },
    ]

    console.log(arrNoRepeat(myArr, 'id'))
    console.log(arrNoRepeat(myArr, 'name'))
    let arr = [1,2,3,4,1]
    console.log(arrNoRepeat(arr))

原网站

版权声明
本文为[Python's path to becoming a God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270537577234.html