Created
January 3, 2018 14:59
-
-
Save iambateman/51ab698717660dbf7f9ecadc7574a0d0 to your computer and use it in GitHub Desktop.
Flatten arbitrary array of numbers in Typescript / Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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