[javascript] 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) {
   list.push(val.artNr);
});

$log.info(list);

The articlelistcontains all 20 objects. For comparing I only need the artNr. 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?

This question is related to javascript arrays angularjs object angularjs-controller

The answer is


You can use indexOf(). Like:

var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.


If you want to search from end to start, use the lastIndexOf() method:

    var Color = ["blue", "black", "brown", "gold"];
    var a = Color.lastIndexOf("brown");
    alert(a);

The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

Returns -1 if the item is not found.


U can use something like this....

  function (field,value) {

         var newItemOrder= value;
          // Make sure user hasnt already added this item
        angular.forEach(arr, function(item) {
            if (newItemOrder == item.value) {
                arr.splice(arr.pop(item));

            } });

        submitFields.push({"field":field,"value":value});
    };

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to angularjs-controller

Check if value exists in the array (AngularJS) How do I inject a controller into another controller in AngularJS Error: [ng:areq] from angular controller How do I use $rootScope in Angular to store variables? AngularJS : The correct way of binding to a service properties Using $setValidity inside a Controller AngularJS: How can I pass variables between controllers?