Search code examples
javascriptarraysiterator

Iterate through two JavaScript arrays with an iterator object using next()


I want to compare two sorted JavaScript arrays with custom objects in them and calculate the differences. I would like to do this using iterator objects to walk through them using next(). (Just as it is possible with iterators in Java.) In the MDN it says:

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is any object which implements the Iterator protocol by having a next() method which returns an object with two properties: value, the next value in the sequence; and done, which is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)

Is there any convenient method to gain an iterator object from an array in JavaScript?


Solution

  • Just like for all iterable objects, to obtain an iterator, access its Symbol.iterator property to get the generator, and call it to get the iterator:

    const arr = ['a', 'b', 'c'];
    const iter = arr[Symbol.iterator]();
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());

    const arr1 = ['a', 'b', 'c'];
    const arr2 = ['a', 'b', 'c'];
    const iter1 = arr1[Symbol.iterator]();
    const iter2 = arr2[Symbol.iterator]();
    
    console.log(iter1.next());
    console.log(iter2.next());
    console.log(iter1.next());
    console.log(iter2.next());