JS数组对象:去重

作者: 意随风起 | 来源:发表于2022-03-21 08:39 被阅读0次
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
    </body>
    <script>
        // 数组对象去重,参数:
        // 1.需要去重数组;2.根据数组对象里的某个字段去重
        function handleUnique(dataList, compareKey) {
            // 存放去重过后的数据
          let arr = []
          let obj = {}
          // 去除data,里面compareKey相同的对象
          for (let i = 0; i < dataList.length; i++) {
                if (!obj[dataList[i][compareKey]]) {
                     arr.push(dataList[i])
                     obj[dataList[i][compareKey]] = true
                }
          }
            return arr
        }
        
        let arr = [
            {
                id: '5',
                title: '5'
            },
            {
                id: '5',
                title: '55'
            },
            {
                id: '1',
                title: '1'
            },
            {
                id: '2',
                title: '2'
            },
            {
                id: '1',
                title: '11111'
            },
            {
                id: '2',
                title: '22'
            },
            {
                id: '2',
                title: '222'
            },
            {
                id: '3',
                title: '3'
            },
            {
                id: '4',
                title: '4'
            }
        ]
        console.log(handleUnique(arr, 'id'))
        
        var arr2 = [
          {name:'zopp',age:0},
          {name:'gpp',age:18},
          {name:'null',age:null},
          {name:'yjj',age:8},
          {name:'yjj',age:'3'},
          {name:'yjj',age:'-3'},
          {name:'yjj',age:-5}
        ];
        // 数组对象排序,参数:需要排序的字段(数字类型)
        function handleCompare(property){
          return (a, b) => {
            const value1 = Number(a[property])
            const value2 = Number(b[property])
            return value1 - value2
          }
        }
        console.log(arr2.sort(handleCompare('age')))
    </script>
</html>

相关文章

网友评论

    本文标题:JS数组对象:去重

    本文链接:https://www.haomeiwen.com/subject/mypodrtx.html