两个数组,把其中ID相同的项去除,返回一个新的数组
var b1=[
{
"ID": 1,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 2,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 3,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 4,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 5,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 6,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 8,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 9,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 10,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 11,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 12,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
}
];

var a1= [
{
"ID": 1,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 2,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 3,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 4,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
},
{
"ID": 5,
"Name": "sample strin",
"ImgUrl": "sample stng 3"
},
{
"ID": 6,
"Name": "sample strin2",
"ImgUrl": "sample string 3"
}
]
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果id相同的项,其name和imgurl字段也是相同的,那么可以直接合并数组,然后用ES6中的将数组转化为Set结构再转回数组结构就去重了
如果id相同,但是name和imgurl字段不同,那就遍历一项一项处理吧
补充:确实数组每一项是对象,用set不行,但是可以变通啊,将每一项的对象转化为字符串啊,而这个转化也很简单,如下
如果数组内部没有重复,只需要把第二个数组元素一个一个取出,然后比对是否在第一个数组中存在,不存在的话就加入第一个数组。当然,如果是排好序的可能会更简单。
伪代码: