Popov Aliev Popov Aliev - 7 months ago 112
AngularJS Question

How to get index of array element in loop?

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
I tried:

angular.forEach($scope.message, function (item, $index) {});


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!