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 articlelist
contains 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?
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
isArray() Function in AngularJS is used to return TRUE if the reference is an array and FALSE if it is not an array. Syntax: angular. isArray(value);
Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise.
You can use unique filter while using ng-repeat . If you use track by $index then unique won't work.
You could use indexOf
function.
if(list.indexOf(createItem.artNr) !== -1) { $scope.message = 'artNr already exists!'; }
More about indexOf:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With