user3999667
user3999667

Reputation:

Check for duplicate items before pushing

Good morning,

I'm wanting to push new items to an array (which we can do) but before pushing check for duplicates to prevent duplicating items within the array.

I've tried this example, unsuccessfully I haven't managed to get this working with our code.

If anyone know of a better solution or can see where we are going wrong please let us know asap. Thank you.

** JS **

 $scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
 $scope.logItem = function($index, brandName, partNumber, productName, amount) {

     $scope.newItem = {
         Brand: brandName,
         Part: partNumber,
         Product: productName,
         Amount: amount
     };

     var duplicateItem = $scope.Products.reduce(function(previous, i) {
         if ($scope.newItem === i) return true;
         return previous
     }, false);

     if (duplicateItem) {
         alert("Already Logged");
     } else {
         alert("Item Logged");
         $scope.Products.push($scope.newItem);
         $scope.$storage.Products = $scope.Products;
     }


 }

** FIX **

$scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
$scope.logItem = function($index, brandName, partNumber, productName, amount) {
    $scope.newItem = {
        Brand: brandName,
        Part: partNumber,
        Product: productName,
        Amount: amount
    };
    var isDuplicate = false;
    $scope.Products.forEach(function(element) {
        if (JSON.stringify(element) === JSON.stringify($scope.newItem)) {
            isDuplicate = true;
            return false;
        }
    });
    if (!isDuplicate) {
        alert("Item Logged");
        $scope.Products.push($scope.newItem);
        $scope.$storage.Products = $scope.Products;
    } else {
        alert("Already Logged");
    };

}

Upvotes: 5

Views: 10386

Answers (4)

Rick
Rick

Reputation: 13490

You can always check if it's safe to push to an array before pushing on to it.

if ($scope.ITEMS.indexOf(ITEM) == -1) {
  // SAFE
  $scope.ITEMS.push(ITEM);
}

Upvotes: 3

Dinesh ML
Dinesh ML

Reputation: 931

Also, you can use _.reject or _.filter functions in underscore.js to prevent the duplicate values based on conditions

Upvotes: 1

Igor Semin
Igor Semin

Reputation: 2496

Something like this

$scope.Products.forEach(function (element) {
    if (JSON.stringify(element) === JSON.stringify($scope.newItem)) {
        isDuplicate = true;
        return false;
    }
});

Look fiddle

Upvotes: 6

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

http://jsfiddle.net/u8Fuk/24/ .

You can use the unique filter. for that you need to add dependecy for angularui, then you can simply do

ng-repeat="item in items | unique:'item' "

Upvotes: 1

Related Questions