Skip to content

Instantly share code, notes, and snippets.

@cblair
Created October 26, 2016 23:40
Show Gist options
  • Save cblair/ce76449383b502fb9c1047ddb0c0f26b to your computer and use it in GitHub Desktop.
Save cblair/ce76449383b502fb9c1047ddb0c0f26b to your computer and use it in GitHub Desktop.
JS Array flatten
'use strict';
/** Function to flatten sub-arrays within an array into one big array.
* @param {Array} origArray - The array to flatten.
*
* @returns {Array} The flattened array.
*/
function flatten(origArray) {
var flattenedArray = [];
// Only do flatten operations if we're working on an array.
if (Array.isArray(origArray)) {
origArray.forEach(function (element) {
// Flattened element if its is a sub-array.
var flattenedSubArray = [];
// If the element is an array, recursively flatten it.
if (Array.isArray(element)) {
flattenedSubArray = flatten(element).map(function (subElement) {
return subElement;
});
// Otherwise, simply get the scalar element.
} else {
flattenedSubArray = [element];
}
// Finally, take the flattened sub-array here in the tail of the
// recursion and push it to the final closed flattened array.
flattenedSubArray.forEach(function (element) {
flattenedArray.push(element);
});
});
}
return flattenedArray;
}
// Tests
// console.log([]);
// console.log(flatten([])); // -> []
// console.log([1,2,3,4]);
// console.log(flatten([1,2,3,4])); // -> [ 1, 2, 3, 4 ]
// console.log([1,2,{simpleNestedObject:true},4]);
// console.log(flatten([1,2,{simpleNestedObject:true},4])); // -> [ 1, 2, { simpleNestedObject: true }, 4 ]
// console.log([1,2,3,[4,5,6,7],8]);
// console.log(flatten([1,2,3,[4,5,6,7],8])); // -> [ 1, 2, 3, 4, 5, 6, 7, 8 ]
// console.log([1,2,3,[4,5,6,7,[8,9]],10]);
// console.log(flatten([1,2,[4,5,6,7,[8,9]],10])); // -> [ 1, 2, 4, 5, 6, 7, 8, 9, 10 ]
// console.log([1,2,[4,5,6,[[7,8],9]],10]);
// console.log(flatten([1,2,[4,5,6,[[7,8],9]],10])); // -> [ 1, 2, 4, 5, 6, 7, 8, 9, 10 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment