1

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

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank soo much for ur Answer
but its not find casesensitive Like Abc vs abc
That's not automatic, you have to turns name into lowercase: return e.EmpName.toLowerCase() === EmpDetails.EmpName.toLowerCase()
u mean return e.EmpName.toLowerCase === EmpDetails.EmpName.toLowerCase;
yes, return e.EmpName.toLowerCase() === EmpDetails.EmpName.toLoweCase();
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.