Skip to content

Instantly share code, notes, and snippets.

@TheMaverickProgrammer
Created August 29, 2016 22:58
Show Gist options
  • Save TheMaverickProgrammer/311a8e3501a07a9661a7469c9576c343 to your computer and use it in GitHub Desktop.
Save TheMaverickProgrammer/311a8e3501a07a9661a7469c9576c343 to your computer and use it in GitHub Desktop.
Flatten is a function that turns a nested array 'glob' and transform it into a linear array
/**************************************************
Author: Maverick Peppers
Date: 8/29/2016
Transform a nested array glob into one linear array
Input:
- Glob. A nested array.
Returns:
- Queue. A linear array.
***************************************************/
function flatten(glob) {
var queue = []; // create a new empty array
// Step through the contents
for(var i = 0; i < glob.length; i++) {
// If the content at i is an array, recusively call this function on the contents
if(Array.isArray(glob[i])) {
// Append the returned array on at the end of the queue
queue = queue.concat(flatten(glob[i]));
} else { // Else, we have an isolated item
queue.push(glob[i]); // simply push it at the end of the array
}
}
// Returns the flattened array contents
return queue;
}
/************************
TESTS
*************************/
function runFlattenTest() {
var test1 = [[1,2,[3]],4];
var out1 = flatten(test1);
// output is [1,2,3,4]
console.log(JSON.stringify(out1));
var test2 = [[[1],2,[3]],4,[6,7,[8],9],5];
var out2 = flatten(test2);
// output is [1,2,3,4,6,7,8,9,5]
console.log(JSON.stringify(out2));
var test3 = [1, 2, 3, 4, 5, []];
var out3 = flatten(test3);
// output is [1,2,3,4,5]
console.log(JSON.stringify(out3));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment