我希望通过删除重复项而不分配给第三个变量来连接两个数组:
var arr1=[{id:1,name:'AB'},{id:2,name:'CD'}];
var arr2=[{id:3,name:'EF'},{id:2,name:'CD'}];
我想要arr1:
[{id:1,name:'AB'},{id:2,name:'CD'},{id:3,name:'EF'}]
arr1.concat(arr2);
答案 0 :(得分:2)
首先合并两个数组,然后将其ID放入数组中。然后根据地图值创建数组。
var arr1=[{id:1,name:'AB'},{id:2,name:'CD'}];
var arr2=[{id:3,name:'EF'},{id:2,name:'CD'}];
arr1 = arr1.concat(arr2) // merge two arrays
let foo = new Map();
for(const tag of arr1) {
foo.set(tag.id, tag);
}
let final = [...foo.values()]
console.log(final)
答案 1 :(得分:1)
可以使用数组reduce和findIndex来实现所需的功能。
var arr1=[{id:1,name:'AB'},{id:2,name:'CD'}];
var arr2=[{id:3,name:'EF'},{id:2,name:'CD'}];
// loop over arr2, add the elements of array2 if it doesn't exist in array1
var newArr = arr2.reduce((acc, eachArr2Elem) => {
if (arr1.findIndex((eachArr1Elem) => eachArr1Elem.id === eachArr2Elem.id && eachArr1Elem.name === eachArr2Elem.name) === -1) {
acc.push(eachArr2Elem)
}
return acc
}, [...arr1]); // initialize the new Array with the contents of array1
console.log(newArr)
答案 2 :(得分:0)
通过使用lodash _.uniqWith(array, [comparator])
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
答案 3 :(得分:0)
使用 public function Functionname(Request $request, $id, $username, $bio)
运算符,您可以展平传递给spread
方法的任意数量的数组,我还为(希望)更具可读性的代码拆分了一些逻辑方法。我希望这会有所帮助。
combineAndDeDup
答案 4 :(得分:0)
<!everyone>
数据变量包含您的唯一数组