Md Ghousemohi
Md Ghousemohi

Reputation: 197

How can i prevent duplicate Record in Array

I need to prevent inserting duplicate Rec in $scope.EmployeeList Array For that i wrote if ($scope.EmployeeList.indexOf(EmpDetails) == -1) but its not filtering my 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....');

Upvotes: 1

Views: 708

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

You can also use Array.prototype.some to find duplicate value.The some() method tests whether at least one element in the array passes the test implemented by the provided function.

var empDetails = {name: 'abc', email: '[email protected]'};

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....');

Upvotes: 1

Faly
Faly

Reputation: 13356

Don't use indexOf (it checks for strict equality), try findIndex:

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

Upvotes: 1

Related Questions