僅保留副本向兩個陣列新增 - 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