User_3535
User_3535

Reputation: 852

How to avoid duplicates to local storage in Angular.js

I use Angular.js localstorage to store the values in local

Here is plnkr Demo

everything works fine but how to avoid inserting a product or a value twice? (how to avoid duplicates) while pushing a value to local

Upvotes: 0

Views: 785

Answers (2)

Fabrice Kabongo
Fabrice Kabongo

Reputation: 668

I think you can use a shorter way than the Nicolas one:

$scope.cloneItem = function (todo) {

    if ($scope.$storage.notes.indexOf(todo) == -1) {
    //if the object is not in the array
        $scope.$storage.notes.push({
            "price": todo.price,
            "id": todo.id,
            "quan": todo.quan
        });
    }
    //else you just do nothing
}

Upvotes: 1

Nicolas
Nicolas

Reputation: 2231

You just push items to an array without any further checks in cloneItem(). You can update its implementation to first check for duplicate (just a quick idea):

$scope.cloneItem = function (todo) {

    // Check for duplicate on id
    if($scope.$storage.notes.filter(function (note) {
      return note.id === todo.id;
    }).length > 0) {
      return;
    };

    // Insert if not duplicate
    $scope.$storage.notes.push({
        "price": todo.price,
        "id": todo.id,
        "quan": todo.quan
    });
}

Upvotes: 2

Related Questions