Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Only push to array if unique

I have an Angular application that collects values of items for an invoice, I want to make sure only unique items are being added to this collection but am having no luck.

I am pushing 3 pieces of information to this collection: id, price, and type. I want to make sure there is nothing in the collection currently matching those 3 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'
    });
    }
}

// Trying to avoid collections like this

invoice: { items: [ { } , { id: 25 price: 0 type: photo } , { id: 25 price: 0 type: photo } ] }

enter image description here

like image 205
xXPhenom22Xx Avatar asked Mar 28 '14 17:03

xXPhenom22Xx


1 Answers

.filter is pretty much what you need.

$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'
    });
    }
}

Semi-contrived JSFiddle

like image 158
SomeKittens Avatar answered Nov 14 '22 21:11

SomeKittens