在包含作为数组的对象的数组中检查重复项

Checking duplicate in an array that contains objects as an array

本文关键字:数组 检查 对象 包含作      更新时间:2023-09-26

我想检查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
                }
            ]
        }
    ]

下面是我尝试过的代码,但执行后没有进入条件。。

outputTypeId为[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;
                }
            }
        }
    }
 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>;
  • 代码行数减少:)

您使用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推入其中。