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中插入重复的Rec。我为它编写的EmployeeList数组($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 个解决方案
#1
1
Don't use indexOf (it checks for strict equality), try findIndex:
不要使用indexOf(它检查严格相等),试试findIndex:
if ($scope.EmployeeList.findIndex(function(e) { return e.EmpName === EmpDetails.EmpName; }) === -1) {
$scope.EmployeeList.push(EmpDetails);
console.log($scope.EmployeeList);
}
#2
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.
您也可以使用Array.prototype。有些是为了找到重复的值。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....');
#1
1
Don't use indexOf (it checks for strict equality), try findIndex:
不要使用indexOf(它检查严格相等),试试findIndex:
if ($scope.EmployeeList.findIndex(function(e) { return e.EmpName === EmpDetails.EmpName; }) === -1) {
$scope.EmployeeList.push(EmpDetails);
console.log($scope.EmployeeList);
}
#2
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.
您也可以使用Array.prototype。有些是为了找到重复的值。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....');