1

I'm looking for iterator for multiple dimension array that I can iterate through the array easily. For example:

var multipeArrayLike = [[1,[21,22],3,4],[5,6,7,8]]
var iterator = getIterator(multipeArrayLike)

console.log(iterator.next().value) // should return 1 
console.log(iterator.next().value) // should return 21
console.log(iterator.next().value) // should return 22
console.log(iterator.next().value) // should return 3
console.log(iterator.next().value) // should return 4
console.log(iterator.next().value) // should return 5
....
console.log(iterator.next().value) // should return 8
1
  • You need to create recursive function which checks for values if values is an array again call this function with that values else if the values is not array return the value; Commented Apr 8, 2016 at 7:07

1 Answer 1

4

You can use a recursive generator in a way similar to this:

'use strict';

function *flat(a) {
    if (!Array.isArray(a)) {
        yield a;
    } else {
        for (let x of a)
            yield *flat(x);
    }
}

var multipeArrayLike = [[1, [21, 22], 3, 4], [5, 6, 7, 8]]


for (let y of flat(multipeArrayLike))
    document.write('<pre>'+JSON.stringify(y,0,3));

Sign up to request clarification or add additional context in comments.

3 Comments

If you add 'use strict'; to your example, it will run in Chrome (at least the version I have).
@FelixKling: works fine here (49.0.2623.110), but added, thanks.
Ah, I'm still on 48.0.2564.116. It doesn't allow block scoped variables in non-strict mode. Looks like I should upgrade :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.