鍍金池/ 問答/HTML5  HTML/ angular 求兩個數(shù)組的差集

angular 求兩個數(shù)組的差集

假如有兩個數(shù)組,怎樣把兩個數(shù)組的差集push進$scope.dataIndex這個數(shù)組啊

如果不引入其他第三方庫的情況下,如何用js 得到差集呢

  let tempData = [5, 6, 8];
  let tempArr = [5, 6, 7, 8];
  $scope.dataIndex = [];
      angular.forEach(tempData, function(item, index) {
          //if (tempArr.indexOf(item.Id) !== -1) {
              // $scope.dataIndex.push(item.Id);
                 //   console.log(item);
              // }
         });
回答
編輯回答
只愛你

引入Underscore.js

_.difference([5,6,7,8],[5,6,8])
// 注意是[5,6,7,8]在前,[5,6,8]在前返回空數(shù)組

結果是[7]

2018年4月6日 10:29
編輯回答
離夢

沒用過angular

let diff = [...new Set([...new Set(tempData )].filter(x => !new Set(tempArr).has(x)))]

數(shù)組取差

2017年9月17日 08:46
編輯回答
尐懶貓

這是我項目里自己寫的 因為有特殊需求要支持對象的差集 那段沒貼出來

diffArray = (arr1, arr2) => {
    for (let i = arr1.length - 1; i >= 0; i--) {
        const a = arr1[i];
        for (var j = arr2.length - 1; j >= 0; j--) {
            let b = arr2[j];
            if (a == b) {
                arr1.splice(i, 1);
                break;
            }
        }
    }
    return arr1;
}

如果支持es6可以用這段

Array.prototype.diff = function(arr) {
    return this.filter(function(i) {return arr.indexOf(i) < 0;});
};

underscore庫有_.difference

2018年6月17日 21:38