用 JavaScript 找出兩個數字陣列中不同元素
我們需要編寫一個 JavaScript 函式,輸入數字陣列後輸出陣列中那些不屬於兩者的元素。
例如,如果兩個陣列為 -
const arr1 = [2, 4, 2, 4, 6, 4, 3]; const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
輸出
那麼輸出應為 -
const output = [ 6, 5, 12, 1, 34 ]
示例
程式碼如下 -
const arr1 = [2, 4, 2, 4, 6, 4, 3];
const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
const deviations = (first, second) => {
const res = [];
for(let i = 0; i < first.length; i++){
if(second.indexOf(first[i]) === -1){
res.push(first[i]);
}
};
for(let j = 0; j < second.length; j++){
if(first.indexOf(second[j]) === -1){
res.push(second[j]);
};
};
return res;
};
console.log(deviations(arr1, arr2));輸出
在控制檯中的輸出 -
[6, 5, 12, 1, 34 ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP