Check if value exists in the array (AngularJS)


Currently, I’m using the forEach()-method of angular to check the new value with the array of objects. But that’s the wrong approach because, for example, in the list are 20 objects. When I’m creating an object with an existing article, then the if-statement in forEach tells one time the article is existing and 19 times it isn’t.

The following code:

var list = [];

articlelist.forEach(function (val) {


The articlelistcontains all 20 objects. For comparing, I only need the artNr. Because when the User creates a new article, then should be an if-Statement to check if the added artNr is already existing.

$scope.createItem = function (createItem) {
  if(list.artNr === createItem.artNr) {
      $scope.message = 'artNr already exists!';

The problem is, that list.artNr returns me "undefined" because the list variable is an array:

list output in console => Array ["AB001", "AB002", "AB003", "AB004"],

createItem output: => Object { artNr: "AB001", description: "New Article" ...}

How can I compare the new created object with the array from the list variable?


You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';

More about indexOf:

Answered By – Juha Tauriainen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published