Hung Tran
Hung Tran

Reputation: 263

Iterator for multiple dimension array in javascript

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

Upvotes: 1

Views: 52

Answers (1)

georg
georg

Reputation: 214959

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));

Upvotes: 4

Related Questions