JavaScript中两个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 ]