Skip to content

Instantly share code, notes, and snippets.

@kenreilly
Last active June 1, 2016 17:21
Show Gist options
  • Save kenreilly/347e68ff434d112bd1ddbfab6669b788 to your computer and use it in GitHub Desktop.
Save kenreilly/347e68ff434d112bd1ddbfab6669b788 to your computer and use it in GitHub Desktop.
TypeScript example class for array flattener
// Flatten nested arrays of numbers into a single-dimension array of numbers
// e.g. [0, 1, [2, 3, [4, 5]]] => [0, 1, 2, 3, 4, 5]
class ArraySquasher {
// Private method - Recursively flatten array
private static recurse(arr: Array<any>): Array<number> {
// Initialize result and process array
var result = [];
for (var i = 0, ii = arr.length; i != ii; ++i) {
var x = arr[i];
if (Array.isArray(x)) {
// Continue recursively processing array
result = result.concat(ArraySquasher.recurse(x));
}
else if (typeof(x) == 'number') {
// Push the number onto the array
result.push(x);
}
}
// Return the flattened array component
return result;
}
// Public method - Take input array and return flattened single-dim array
public static flatten(arr: Array<any>): Array<number> {
// Kick off array processing and return the result
return [].concat(ArraySquasher.recurse(arr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment