如何防止在Array中重复记录

时间:2017-11-16 06:23:05

标签: angularjs

我需要阻止在$scope.EmployeeList数组中插入重复的Rec为我写的($scope.EmployeeList.indexOf(EmpDetails) == -1)但是它没有过滤我的rec

 $scope.EmployeeList = [];
        var amtArray = [];
        $scope.G_Total = "Total Amount is";
        $scope.SaveDb = function (Isvalid) {
            var EmpDetails = {
                'EmpName': $scope.EmpName,
                'Email': $scope.Email,
                'Cost': $scope.cost

            }
            if ($scope.EmployeeList.indexOf(EmpDetails) == -1) {
                $scope.EmployeeList.push(EmpDetails);
                console.log($scope.EmployeeList);
            }
            else
                alert('Duplicate Value....');

2 个答案:

答案 0 :(得分:1)

不要使用 indexOf (它会检查严格的相等性),请尝试 findIndex

if ($scope.EmployeeList.findIndex(function(e) { return e.EmpName === EmpDetails.EmpName; }) === -1) {
    $scope.EmployeeList.push(EmpDetails);
    console.log($scope.EmployeeList);
}

答案 1 :(得分:1)

您还可以使用Array.prototype.some查找重复值。some()方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。

var empDetails = {name: 'abc', email: 'a@gmail.com'};

let duplicate = $scope.EmployeeList.some(function (emp) {
  return emp.name === empDetails.name && emp.email === empDetails.email;
});

if (!duplicate) {
   $scope.EmployeeList.push(EmpDetails);
}
else
   alert('Duplicate Value....');