How to Get the Array Index or Iteration Number with an Each Iterator

Is there a way to access an iteration-counter in Java's for-each loop?

No, but you can provide your own counter.

The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).

How do you get the index of the current iteration of a foreach loop?

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

The concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

Java, How do I get current index/key in for each loop

You can't, you either need to keep the index separately:

int index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}

or use a normal for loop:

for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}

The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"

Get the current index of a for each loop iterating an ArrayList

Just use a traditional for loop:

for (int i = 0; i < yourArrayList.size(); i ++) {
// i is the index
// yourArrayList.get(i) is the element
}

How to iterate a loop with index and element in Swift

Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated() method to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:

for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}

Before Swift 3.0 and after Swift 2.0, the function was called enumerate():

for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}

Prior to Swift 2.0, enumerate was a global function.

for (index, element) in enumerate(list) {
println("Item \(index): \(element)")
}

Accessing the index in 'for' loops

Use the built-in function enumerate():

for idx, x in enumerate(xs):
print(idx, x)

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.

Check out PEP 279 for more.

How to get the current loop index when using Iterator?

Use your own variable and increment it in the loop.

How can I iterate over an element in an array but not move from the index until a condition is fulfill?

You could start from index 1, because you can not change the value at index 0 because of the missing previous value.

Inside the loop increment the value until it is greater than the value at the last index.

const array = [1, 1, 1]

for (let i = 1; i < array.length; i++) {
while (array[i] <= array[i - 1]) array[i]++;
}

console.log(array);

Get loop counter/index using for…of syntax in JavaScript

for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

Or ES6’s Array.prototype.entries, which now has support across current browser versions:

for (const [i, value] of myArray.entries()) {
console.log('%d: %s', i, value);
}

For iterables in general (where you would use a for…of loop rather than a for…in), there’s nothing built-in, however:

function* enumerate(iterable) {
let i = 0;

for (const x of iterable) {
yield [i, x];
i++;
}
}

for (const [i, obj] of enumerate(myArray)) {
console.log(i, obj);
}

demo

If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.



Related Topics



Leave a reply



Submit