Skip to content

Instantly share code, notes, and snippets.

@iambateman
Created January 3, 2018 14:59
Show Gist options
  • Save iambateman/51ab698717660dbf7f9ecadc7574a0d0 to your computer and use it in GitHub Desktop.
Save iambateman/51ab698717660dbf7f9ecadc7574a0d0 to your computer and use it in GitHub Desktop.
Flatten arbitrary array of numbers in Typescript / Angular
testArray:Array<any> = [10, [9,8,7],6, [5, [4,3,2], 1], 10,9,8];
flatten(list:Array<any>) {
let flattened:Array<number> = [];
// For each item in the provided list, check to see if it's a number.
// if it's not, recurse with the sub-array and add those items.
for (let item of list) {
if (typeof item === "number") {
flattened.push(item);
} else {
flattened = [...flattened, ...this.flatten(item)];
}
}
return flattened;
}
let flattenedArray = this.flatten(this.testArray);
console.log(flattenedArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment