⼩程序两个数组的去重操作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){
thinkphp3flag = false
break
}
}
if(flag){
this.setData({
arr1:this.at(this.data.arr1.push(a2[i]))
})
}
}
}
** 第⼀个for循环是 循环来源数据,第⼆for循环是循环已有数据,然后通过⽐较返回全部数据 **
== flag ⽤于判断是否重复,循环已有数据时,如果存在唯⼀属性相等(本题是id)则flag 为false,也就是排除。 == ** 最后在进⾏组装连接形成新的arr1数组 **
3、结果如下:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论