Convert array to iterator

Viewed 2155

How do I convert an array to an iterator, such that I can call both next and done to iterate the array's values?

I've seen exhaustively that

an array is an iterable

but it doesn't have either property (const a = [1,2,3]; a.done; // returns undefined).

I've tried directly accessing the Symbol.iterator (const iter = a[Symbol.iterator];), but it simply returns function values() for the array.

4 Answers

You can use the .entries() method.

const a = [1, 2, 3];

const iterator = a.entries();

console.log(iterator.next().value, iterator.next().done);

I am not sure what you wanted to get with a.done but done is in return object of iterable protocol when next() is being called.

You are right that a[Symbol.iterator] returns value() function as it is described at MDN Web Docs Array.prototype[@@iterator]() but thats exactly what you need if you want to iterate through array with iterator. You can see example below:

const arr = [1,2,3];
const eArr = arr[Symbol.iterator]();
console.log(eArr.next().done);
console.log(eArr.next().done);
console.log(eArr.next().done);
console.log(eArr.next().done);

Alternatively, I could've called the function returned from Symbol.iterator:

const iter = a[Symbol.iterator]();
const first = iter.next();

It was my misinterpretation that done was on the iterator, but it's on the nodes, and can be called as first.done


Inspired by John's answer, I discovered the values() method on arrays (which is what Symbol.iterator is returning in Jax-p's answer) that acts pretty much identically but removes the destructuring step. To summarise the answers:

const a = [1,2,3];

const symbolIterator = a[Symbol.iterator];
const firstSymbolValue = symbolIterator.next();

const valuesIterator = a.values();
const firstValuesValue = valuesIterator.next();

const entriesIterator = a.entries();
const [firstEntriesIndex, firstEntriesValue] = entriesIterator.next();

expect(firstSymbolValue).toBe(1);
expect(firstValuesValue).toBe(1);
expect(firstEntriesValue).toBe(1);

Use the .values() method, it returns an iterator over array elements.

Related