2015-12-18 94 views
3

我要檢查是否存在重複的output數組對象outputTypeId數組檢查重複..中包含的對象作爲數組

下面是JSON:

$scope.entities= [ 
     { 
      "input": { 
       "id": 134 
      }, 
      "output": [ 
       { 
        "id": 135, 
        "outputTypeId": 4 
       } 
      ] 
     }, 
     { 
      "input": { 
       "id": 134 
      }, 
      "output": [ 
       { 
        "id": 135, 
        "outputTypeId": 7 
       } 
      ] 
     }, 
     { 
      "input": { 
       "id": 134 
      }, 
      "output": [ 
       { 
        "id": 135, 
        "outputTypeId": 9 
       } 
      ] 
     } 
    ] 

下面是代碼我試過但它沒有在執行後的條件下..

讓我[7]我檢查多個outputTypeId的,因此一個數組

$scope.checkForDuplicateOutputs = (outputTypeId) => { 
     for (var i = 0; i < $scope.entities.length; i++) { 
      for (var j = i; j < $scope.entities[i].output[j].length; j++) { 

       if (outputTypeId.contains($scope.entities[i].output[j].outputTypeId)) { 
        $scope.isDuplicateOutput = true; 
        break; 
       } else { 
        $scope.isDuplicateOutput = false; 

       } 
      } 
     } 
    } 
+0

嘗試grep將幫助 –

回答

1
function checkForDuplicates(outputTypeIds) { 
     $scope.isDuplicateOutput = $scope.entities.some(function(entity) { // Loop through entities 
      return entity.output.some(function(entityOutput) { // Look for any output 
       return outputTypeIds.indexOf(entityOutput.outputTypeId) != -1; // which is duplicated in 'outputTypeIds' 
      }); 
     }); 
    } 

所以這個解決方案使用Array.some - 它有幾個優點:

  • ,就不再需要手動break您的循環
  • 沒有必要有ij變量來跟蹤循環計數器
  • 無需複製$scope.isDuplicateOutput = <boolean>;
  • 較少的代碼行:)
0

您只打破了break語句的內部循環,問題在於即使重複標誌設置爲true,它在下一次迭代中也會重置爲false。基本上,最終你只會得到最後一次迭代的結果。

最快的解決辦法是使用一個標誌來表示外部環路是否需要停止:

$scope.checkForDuplicateOutputs = (outputTypeId) => { 
    var breakOut = false;     // <--- this is new 
    for (var i = 0; i < $scope.entities.length; i++) { 
     if (breakOut) break;    // <--- this is new 
     for (var j = i; j < $scope.entities[i].output[j].length; j++) 
      if (outputTypeId.contains($scope.entities[i].output[j].outputTypeId)) { 
       $scope.isDuplicateOutput = true; 
       breakOut = true;   // <--- this is new 
       break; 
      } else { 
       $scope.isDuplicateOutput = false; 
      } 
     } 
    } 
} 

如果你還想要遍歷所有實體,擁有所有副本的列表,你可以創建一個數組$scope.isDuplicateOutput,並且只需將重複id插入它。

相關問題