合并并移除 JavaScript 数组中的重复项
假设我们有两个这样的数组 −
const arr1 = [2, 4, 5, 3, 7, 8, 9]; const arr2 = [1, 4, 5, 2, 3, 7, 6];
我们需要编写一个 JavaScript 函数,该函数接受这两个数组,并返回一个包含所有不重复项(仅出现一次)的新数组。
例
代码如下 −
const arr1 = [2, 4, 5, 3, 7, 8, 9];
const arr2 = [1, 4, 5, 2, 3, 7, 6];
const mergeArrays = (first, second) => {
const { length: l1 } = first;
const { length: l2 } = second;
const res = [];
let temp = 0;
for(let i = 0; i < l1+l2; i++){
if(i >= l1){
temp = i - l1;
if(!res.includes(first[temp])){
res.push(first[temp]);
};
}else{
temp = i;
if(!res.includes(second[temp])){
res.push(second[temp]);
};
};
};
return res;
};
console.log(mergeArrays(arr1, arr2));输出
控制台输出 −
[ 1, 4, 5, 2, 3, 7, 6, 8, 9 ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP