Created
January 13, 2019 02:26
-
-
Save CaspianCanuck/d6274b264f123e58ad517be8d03bd996 to your computer and use it in GitHub Desktop.
JS prototype method that flattens an array that contains nested arrays
This file contains hidden or 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
/** | |
* 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