JS返回两个数组中的不同元素或相同元素

一、返回两个数组中的不同元素

  • 使用forEach
diffArr = (arr1, arr2) => {
    let newArr = [];
    arr1.forEach((itm) => {
      let itmStr = itm.toString();
      let temp = arr2.every(ele => itmStr !== ele.toString());
      if (temp) {
        newArr.push(itm);
      }
    });
    arr2.forEach((itm) => {
      let itmStr = itm.toString();
      let temp = arr1.every(ele => itmStr !== ele.toString());
      if (temp) {
        newArr.push(itm);
      }
    });
    return newArr;
  };
  • 使用filter
diffArr = (marr1, marr2) => {
   const eleIsNotInArr = (ele, arr) => arr.every(m => m !== ele) 
    let newArr1 = marr1.filter(x => eleIsNotInArr(x, marr2));
    let newArr2 = marr2.filter(x => eleIsNotInArr(x, marr1));
    return newArr1.concat(newArr2)
  };

二、返回两个数组中的相同元素

使用filter

  getSameEle = (marr1, marr2) => {
       const eleIsInArr = (ele, arr) => arr.some(m => m === ele);
       return marr1.filter(x => eleIsInArr(x, marr2))
  };

你可能感兴趣的:(JS返回两个数组中的不同元素或相同元素)