I have an loop Angular JS:
angular.forEach($scope.message, function (item) {
return (item.id_user == input.id_user) ? true : false;
});
How to get index of array element in loop for each item
?
I tried:
angular.forEach($scope.message, function (item, $index) {});
Using enumerate() method to access index enumerate() is mostly used in for loops where it is used to get the index along with the corresponding element over the given range.
You can access the index even without using enumerate() . Using a for loop, iterate through the length of my_list . Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index] .
An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.
How to Get the Index in a for…of Iteration. Use JavaScript's Array#entries method to create an array iterator. This iterator returns a key-value-pair for each index-value combination in the array. Enjoy!
Sorry for all the vitriol of the community. You're very close to your solution but are a bit confused by documentation. It's okay, let me help clarify!
In the documentation for angular.forEach you will see the following statement:
Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key, obj), where value is the value of an object property or an array element, key is the object property key or array element index and obj is the obj itself. Specifying a context for the function is optional.
And then the following example:
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
Essentially, the code is like this:
angular.forEach('name of list/array you want to loop through', 'callback function to be called for each element of the list')
The important part that you're missing is that the 'callback...' mentioned above can be handed 3 variables which you can then use in your callback. Your callback will be called for each element in the list. Here is some explanation of those 3 variables:
Value: The value of the i-th element/property in the list/array/object
Key: i - the index belonging to the current item in the array
Object: the the object itself (or array/list itself)
Here is an example i put together for you where I use the Key to create a new string showing the index of each letter in $scope.message. Hope this helped!
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