Skip to content

Instantly share code, notes, and snippets.

@wangziling
Created July 5, 2018 16:57
Show Gist options
  • Save wangziling/75b645e842867f2c400822ef8c467683 to your computer and use it in GitHub Desktop.
Save wangziling/75b645e842867f2c400822ef8c467683 to your computer and use it in GitHub Desktop.
Use es6 method - Generator, to flatten multidimensional array.
// method
const flat = function *(arr) {
const {length} = arr;
for(let i = 0; i< length; i++) {
const item = arr[i];
if(Array.isArray(item)){
yield* flat(item);
} else {
yield item;
}
}
}
// main
const flatten = function (arr) {
return [...flat(arr)];
}
// try
const array = [1, [[2, ['a', 'b', ['c', ['d']]], 3], 4], [5, 6]];
console.log(flatten(array)); // [1, 2, "a", "b", "c", "d", 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment