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
asked Apr 8, 2016 at 7:02
Hung Tran
2631 gold badge3 silver badges9 bronze badges
-
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;itzmukeshy7– itzmukeshy72016年04月08日 07:07:10 +00:00Commented Apr 8, 2016 at 7:07
1 Answer 1
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));
answered Apr 8, 2016 at 7:13
georg
216k57 gold badges324 silver badges401 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Felix Kling
If you add
'use strict'; to your example, it will run in Chrome (at least the version I have).georg
@FelixKling: works fine here (49.0.2623.110), but added, thanks.
Felix Kling
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
lang-js