微信小程序两个数组的去重操作

1、tran.js 存在两个不同但却有相同属性值的数组(arr1,arr2):

data: {

    arr1:[
      {
        "id":1,
        "name":"html",
        "read":108987
      },
      {
        "id":2,
        "name":"css",
        "read":5489564
      },
      {
        "id":3,
        "name":"javascript",
        "read":523698
      },
      {
        "id":4,
        "name":"php",
        "read":6985649
      }
    ],
    arr2:[
      {
        "id":1,
        "name":"html",
        "read":108987
      },
      {
        "id":2,
        "name":"css",
        "read":5489564
      },
      {
        "id":3,
        "name":"javascript",
        "read":523698
      },
      {
        "id":4,
        "name":"php",
        "read":6985649
      },
      {
        "id":5,
        "name":"thinkphp",
        "read":9898774
      },
      {
        "id":6,
        "name":"python",
        "read":6888768
      },
      {
        "id":7,
        "name":"wx",
        "read":50123698
      },
      {
        "id":8,
        "name":"game",
        "read":58496491
      }
      ,{
        "id":9,
        "name":"youxiu",
        "read":58496491
      },
      {
        "id":10,
        "name":"niubi",
        "read":58496491
      }
    ]
  },

2、定义一个函数getData进行去重操作:

// 去重操作
  getdata(){
    const a1 = this.data.arr1
    const a2 = this.data.arr2

    for(let i=0,len=a2.length;i<len;i++){
      let flag = true
      for (let j = 0; j < a1.length; j++) {
        if(a2[i].id === a1[j].id){
             flag = false
             break
        }
      }
      if(flag){
        this.setData({
           arr1:this.data.arr1.concat(this.data.arr1.push(a2[i]))
        })
      }
    }
    
  }

** 第一个for循环是 循环来源数据,第二for循环是循环已有数据,然后通过比较返回全部数据 **

== flag 用于判断是否重复,循环已有数据时,如果存在唯一属性相等(本题是id)则flag 为false,也就是排除。 ==

** 最后在进行组装连接形成新的arr1数组 **

3、结果如下:
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值