题干:
两个数组 var A = [1, 5, 6]; var B = [2, 6, 7],实现一个方法,找出仅存在于A 或者 仅 存在于B中的所有数字
找出不同元素
方法一:
// 方法一: const filterArr = (arr1, arr2) => { const arr = [...arr1, ...arr2]; const newArr = arr.filter((t) => { return !(arr1.includes(t) && arr2.includes(t)); }); return newArr; };
方法二:
// 方法二 const filterArr2 = (arr1, arr2) => { // const newArr = arr1.contact(arr2); return arr1.concat(arr2).filter((t, i, arr) => { return arr.indexOf(t) === arr.lastIndexOf(t); }); };
方法三:
// 方法三 const arr1 = A.filter((t) => !B.includes(t)); const arr2 = B.filter((x) => !A.includes(x)); const newArr = arr1.concat(arr2);
找出相同的元素
方法一:
const filterArr = (arr1, arr2) => { let result = []; for (let i = 0; i < arr1.length; i++) { for (let j = 0; j < arr2.length; j++) { if (arr1[i] === arr2[j]) { result.push(arr1[i]); } } } return result; };
方法二:
const filterArr = (arr1, arr2) => { return arr1.filter((t) => { return arr2.includes(t); }); };
方法三:
const filterArr = (arr1, arr2) => { return arr1.filter((t) => { return arr2.indexOf(t) !== -1; }); };