Angular - only push an array if it is unique

I have an Angular app that collects item values ​​for an invoice, I want to make sure that only unique items are added to this collection, but I'm out of luck.

I click 3 pieces of information in this collection: id, price and type. I want to make sure that there is nothing in the collection that matches these three points.

// My container
$scope.invoice = {
    items: [{
    }]
}


    $scope.addPhoto = function() {
    console.log('Withdrawing Photo: '+ $scope.item.id);
    if ($scope.invoice.items.indexOf(item.id) != $scope.item.id)
    {
      $scope.invoice.items.push({
        id: $scope.item.id,
        price: $scope.item.price,
        type: 'photo'
    });
    }
}

// Try to avoid such collections

account: {Items: [{}, {id: 25 price: 0 Type: photo}, {id: 25 price: 0 Type: photo}]}

enter image description here

+4
source share
3 answers

This is the solution I came across in order to solve my problem, hope this helps someone else.

    $scope.addPhoto = function () {
    console.log('Withdrawing Photo: ' + $scope.item.id);
    var newItemId = $scope.item.id;
    var newItemPrice = $scope.item.price;
    var newItemType = 'photo';
    var matches = true;


    // Make sure user hasnt already added this item
    angular.forEach($scope.invoice.items, function(item) {
        if (newItemId === item.id && newItemPrice === item.price && newItemType === item.type) {
            matches = false;
            $scope.message = 'You have already selected to withdraw this item!';
        }
    });

    // add item to collection
    if (matches != false) {
        $scope.invoice.items.push({
            id: $scope.item.id,
            price: $scope.item.price,
            type: 'photo'
        });
        $scope.total += $scope.item.price;
        $scope.message = 'Total Amount Selected';
    }
};
+2
source

.filter - , .

$scope.addPhoto = function() {
    console.log('Withdrawing Photo: '+ $scope.item.id);
    var matches = $scope.invoice.items.filter(function(datum) {
      return datum.id === $scope.item.id &&
        datum.price === $scope.item.price &&
        datum.type === $scope.item.type;
    });
    if (!matches.length)
    {
      $scope.invoice.items.push({
        id: $scope.item.id,
        price: $scope.item.price,
        type: 'photo'
    });
    }
}

JSFiddle

+7

array.splice(array.pop(item));
+1

Source: https://habr.com/ru/post/1533957/


All Articles