Skip to content

Instantly share code, notes, and snippets.

@CaspianCanuck
Created January 13, 2019 02:26
Show Gist options
  • Save CaspianCanuck/d6274b264f123e58ad517be8d03bd996 to your computer and use it in GitHub Desktop.
Save CaspianCanuck/d6274b264f123e58ad517be8d03bd996 to your computer and use it in GitHub Desktop.
JS prototype method that flattens an array that contains nested arrays
/**
* Flattens the array that contains nested arrays, optionally removing null or undefined elements.
* @example
* // returns [1, 2, 3, null, undefined, 4]
* [[1,2,[3,null],undefined],4].flatten()
* @example
* // returns [1, 2, 3, 4]
* [[1,2,[3,null],undefined],4].flatten(true)
* @param removeBlanks {boolean} If evaluates to true, strips any null or undefined array elements.
* @returns {Array} Flattened array of elements of the original array and any of its nested arrays.
*/
Array.prototype.flatten = function(removeBlanks) {
removeBlanks = removeBlanks || false;
var result = [];
function _flatten(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (el != null && typeof el === "object" && typeof el.length !== "undefined") {
_flatten(el);
}
else if (!removeBlanks || (typeof el !== "undefined" && el !== null)) {
result.push(el);
}
}
}
_flatten(this);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment