我有两个数组。元素相同,但值可以不同。 我需要查看它们匹配的两个元素是.fromSourceId和.toSourceId
我要比较的两个数组是userCompareData和userData。元素的数量会发生变化。最后,我看到userComparedata是否在userData中匹配,如果它不存在则添加到createChange
因此,如果userCompareData.toSourceId = userData.toSourceId和userCompareData.fromSourceId = userData.fromSourceId,我不需要将匹配的userCompareData添加到createChange方法。
addPermissionsForCopy = function(){
for (var i = 0; i < $scope.userData.length; i++) {
isFound = false;
for (var j = 0; j < $scope.userCompareData.length; j++) {
if ($scope.userCompareData[j].fromSourceID === $scope.userData[i].fromSourceID) {
if ($scope.userCompareData[j].toSourceID === $scope.userData[i].toSourceID) {
isFound = true;
}
}
}
if (isFound === false) {
$scope.createChange($scope.userCompareData[i].fromSourceID, $scope.userCompareData[i].toSourceID, true, $scope.selectedUserName);
}
}
};
这并不是很正确,因为每次调用此方法时,数据中的元素数量都会不同。 userData可能包含6个项目,然后接下来的2个与userCompareData相同。
答案 0 :(得分:1)
反转这些循环,以便您可以保存未找到的索引:
addPermissionsForCopy = function(){
for (var i = 0; i < $scope.userCompareData.length; i++) {
isFound = false;
for (var j = 0; j < $scope.userData.length; j++) {
if ($scope.userCompareData[i].fromSourceID === $scope.userData[j].fromSourceID) {
if ($scope.userCompareData[i].toSourceID === $scope.userData[j].toSourceID) {
isFound = true;
}
}
}
if (isFound === false) {
$scope.createChange($scope.userCompareData[i].fromSourceID, $scope.userCompareData[i].toSourceID, true, $scope.selectedUserName);
}
}
};
答案 1 :(得分:0)
Try angular.forEach():
var isFound=false;
angular.forEach(userCompareData, function(userComVal){
angular.forEach(userData, function(userDataVal){
if(userComval==userDataVal){
//do what you want on true
isFound=true;
}else{
isFound=false;
}
});
if(isFound==false){
//do what you want
$scope.createChange($scope.userCompareData[i].fromSourceID, $scope.userCompareData[i].toSourceID, true, $scope.selectedUserName);
}
});