Created
August 3, 2018 01:40
-
-
Save tinkertrain/741dcc95b1a4a7c8389d8cea2593f2f5 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
This file contains 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
/** | |
* Function that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers | |
* @param arr The array to flatten | |
* @param removeNonItems A flag to remove `undefined` and `null` values if set to true | |
* | |
* @returns Array | |
*/ | |
function flatten(arr, removeNonItems = false) { | |
var nested = false; | |
var flattened = arr.reduce(function(initial, item) { | |
// Skip `undefined` and `null` items if the flag removeNonItems = true | |
// check if they are `undefined` and `null` by using `== null`, we still want zeros | |
if (removeNonItems && item == null) { | |
return initial; | |
} | |
if (Array.isArray(item)) { | |
nested = true; | |
} | |
return initial.concat(item); | |
}, []); | |
return nested ? flatten(flattened) : flattened; | |
} | |
var test = [ | |
[1, 2, 4, [12, [6]]], | |
3, 0, null, undefined | |
]; | |
var flattened = flatten(test); // [ 1, 2, 4, 12, 6, 3, 0, null, undefined ] | |
var flattened2 = flatten(test, true); // [ 1, 2, 4, 12, 6, 3, 0 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment