我有两个数组想要组合,然后在出现重复项时消除这两个值。我怎样才能实现这个目标?
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,5,6,7]
我想留下 arr3 = [1,2,4]
谢谢
可以使用filter方法只保留那些不重复的元素。如果某个元素在组合数组中出现多次,则该元素被视为重复。
const arr1 = [1, 2, 3, 4, 5, 6, 7];
const arr2 = [3, 5, 6, 7];
const combinedArray = arr1.concat(arr2);
const resultArray = combinedArray.filter(item => {
// Count the occurrence of the current item in the combined array
const occurrence = combinedArray.filter(x => x === item).length;
// Keep the item only if its occurrence is exactly 1
return occurrence === 1;
});
console.log(resultArray); // Output: [1, 2, 4]