处理数组场景总结

·  阅读 68
处理数组场景总结

数组过滤

      let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      let arr2 = [1, 2, 6]
      arr2.forEach((item, index) => {
        arr.forEach((ele, i, self) => {
          if (item === ele) {
            self.splice(i, 1)
          }
        })
      })
      console.log(arr) // [3, 4, 5, 7, 8, 9, 10]
复制代码

根据某个字段分组

        let arr = [
            {
                groupCheckBasis: 3,
                groupIndex: 3,
                groupNumber: 2
            },
            {
                groupCheckBasis: 3,
                groupIndex: 2,
                groupNumber: 2
            },
            {
                groupCheckBasis: 3,
                groupIndex: 1,
                groupNumber: 2
            },
            {
                groupCheckBasis: 3,
                groupIndex: 2,
                groupNumber: 3
            },
            {
                groupCheckBasis: 3,
                groupIndex: 2,
                groupNumber: 1
            },
            {
                groupCheckBasis: 3,
                groupIndex: 1,
                groupNumber: 1
            },
            {
                groupCheckBasis: 3,
                groupIndex: 1,
                groupNumber: 3
            }
        ]
        let obj = {}
        arr.forEach(item => {
            if (!obj[item.groupNumber]) {
                obj[item.groupNumber] = []
            }
            obj[item.groupNumber].push(item)
        })
        console.log(obj)
复制代码

数组中根据某个字段去重

方案1

       let data = [
            {
                name: 'ZYTX'
            },
            {
                name: 'ZYTA'
            },
            {
                name: 'ZDTX'
            },
            {
                name: 'ZYTX'
            }
        ]
        let hash = {}
        let newData=[]
        data.forEach(item => {
            if (!hash[item.name]) {
                hash[item.name] = true
                newData.push(item)
            }
        })
        console.log(newData)
复制代码

方案2

     let data = [
            {
                name: 'ZYTX'
            },
            {
                name: 'ZYTA'
            },
            {
                name: 'ZDTX'
            },
            {
                name: 'ZYTX'
            }
        ]
        let hash = {}

        let newData = data.reduce(function (item, current) {
            if (!hash[current.name]) {
                hash[current.name] = true
                item.push(current)
            }
            return item
        }, [])
        console.log(newData)
复制代码

两个数组对象取相同的值

     let arr= []
      for (let i = 0; i < appData.length; i++) {
        let itemData = list.find((item, index) => {
          return item.appId === appData[i]
        })
        arr.push(itemData.name)
      }
     console.log(arr)
复制代码
分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改