2016-06-10 43 views
0

我想比較,「項目」陣列和copyofOpList陣列中的項目copyofOpList從陣列比較它的其他陣列

檢索數據出現刪除數據,這是我嘗試:

var _deleteUsedElement1 = function(item) { 

        for (var i = 0; i < item.length-1; i++){  
          for (var j = 0; j< $scope.copyofOpList.length-1; j++){ 
         if (item[i].operationCode == $scope.copyofOpList[j].code) { 
         $scope.copyofOpList.splice(j, 1); 

         } } } }; 

$scope.compareArrays = function() { 
    ...Get data from web Service 
    _deleteUsedElement1(item); 
    } 

copyofOpList數組有14個元素,而item數組有2個數組 但我的代碼只刪除了一個出現(第一個),所以請如何更正我的代碼,以檢索copyofOpList數組中的任何出現item array 感謝幫助

回答

3

我會盡量避免在循環中循環 - 這既不是非常優雅的,也不是一個非常有效的方式得到你想要的結果。

這裏的東西更優雅,最有可能更有效:

var item = [1,2], copyofOpList = [1,2,3,4,5,6,7]; 

var _deleteUsedElement1 = function(item, copyofOpList) { 
    return copyofOpList.filter(function(listItem) { 
    return item.indexOf(listItem) === -1; 
    }); 
    }; 

    copyofOpList = _deleteUsedElement1(item, copyofOpList); 
    console.log(copyofOpList); 
    //prints [3,4,5,6,7] 
} 

而且因爲我剛纔注意到,您比較的對象的屬性,下面是匹配對象屬性過濾器版本:

var item = [{opCode:1},{opCode:2}], 
    copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]; 

var _deleteUsedElement1 = function(item, copyofOpList) { 
     var iOpCodes = item.map(function (i) {return i.opCode;}); 
     return copyofOpList.filter(function(listItem) { 
     return iOpCodes.indexOf(listItem.opCode) === -1; 
     }); 
    }; 

copyofOpList = _deleteUsedElement1(item, copyofOpList); 
console.log(copyofOpList); 
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}] 

這樣做的另一個好處是你可以避免修改你的陣列,而你仍然在使用它們,這是JonSG和Furhan S.在答案中提到的一個積極影響。

+1

感謝先生的回覆:) – Jina

+0

這就是非常優雅和簡潔。雖然我想指出它仍然在循環中循環,因爲indexOf()本身就是一個循環:) –

+0

隨着您的編輯,這涵蓋了我的答案,所以我將刪除它。 – JonSG

2

拼接會改變你的陣列。使用新值的臨時緩衝區數組是這樣的:

var _deleteUsedElement1 = function(item) { 
    var _temp = []; 
    for (var i = 0; i < $scope.copyofOpList.length-1; i++){  
     for (var j = 0; j< item.length-1; j++){ 
      if ($scope.copyofOpList[i].code != item[j].operationCode) { 
       _temp.push($scope.copyofOpList[j]); 
      } 
     } 
    } 
    $scope.copyofOpList = _temp; 
}; 
+2

你測試過了嗎?我認爲它不會滿足請求者的需求。 – Tex

+1

@Tex你是對的。第一次沒有測試,希望編輯後的代碼能夠按照我的理解進行必要的操作。 Thnx指出。 –

+1

嘿,檢查過濾器(),它是做你正在做什麼_temp – JonSG