寻找两个数组之间的差异 - JavaScript
我们有两个这样的数字数组 -
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
我们要求编写一个 JavaScript 函数,该函数接收这两个数组,并返回不是这两个数组中公有元素的元素。
示例
以下是代码 -
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const difference = (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(difference(arr1, arr2));输出
这将在控制台中产生以下输出 -
[ 6, 5, 1 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP