js 对象数组去重

 

      let tempData = [
        {
          id: 1,
          title: 'a',
        },
        {
          id: 1,
          title: 'b',
        },
        {
          id: 2,
          title: 'c',
        },
      ]
      //两次循环
      let resultData = []
      for (let i = 0; i < tempData.length; i++) {
        let repeat = false
        for (let j = 0; j < resultData.length; j++) {
          if (tempData[i].id === resultData[j].id) {
            repeat = true
            break
          }
        }
        if (!repeat) {
          resultData.push(tempData[i])
        }
      }
      console.log(resultData)

      //一次循环
      let map = new Map()
      tempData.forEach((item) => {
        map.set(item.id, item)
      })
      const resultData2 = [...map.values()]
      console.log(resultData2)

      //一次循环
      const obj = {}
      const resultData3 = tempData.reduce((total, next) => {
        if (!obj[next.id]) {
          obj[next.id] = true
          total.push(next)
        }
        return total
      }, [])
      console.log(resultData3)

猜你喜欢

转载自blog.csdn.net/xutongbao/article/details/125682413
今日推荐