yuro yuro - 8 months ago 502
Javascript Question

Check if value exists in the array (AngularJS)

Currently I'm using the

-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) {


contains all 20 objects. For comparing I only need the
. Because when the User create a new article then should be an if-Statement to check if the added artNr is already exists.

$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: