M
M
microf2015-10-10 10:14:06
JavaScript
microf, 2015-10-10 10:14:06

How to find if an element is in an array?

Basics of the basics. I'm adding to cart

var     ProductsList = [],
                Cart = function (id, name) {
                    this.id = id;
                    this.name = name;
                };

  function addProduct(id, name) {

            var newItem = new Cart(id, name);
               ProductList.push(newItem);
                                   }

It is necessary that if the element with the id is already in the Cart, then do not add it (well, do a return). As I understand it, you can use
angular.forEach(Cart, function(id) {
// и вот здесь понять не могу как сравнить приходящий id с Cart.id
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vitaly Inchin ☢, 2015-10-10
@microf

var ProductsList = [],
      Cart = function (id, name) {
           this.id = id;
           this.name = name;
       }
;

function addProduct(id, name) {
      ProductsList.some(function(e){
         return e.id == id;
      })||ProductsList.push(new Cart(id, name));
}

S
Stopy, 2015-10-10
@Stopy

Insert not into an array, but into another object, like this { id: {name: name} }, and the check for existence in the basket will solve itself

P
profesor08, 2015-10-10
@profesor08

According to the angular.forEach documentation , iterating over the elements should look like this for your example.

angular.forEach(ProductsList, function(value, key) {

}

E
Evgeny Petrov, 2015-10-10
@EvgenZZ

underscore. js underscorejs.ru/#arrays

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question