Skip to content

Instantly share code, notes, and snippets.

@tinkertrain
Created August 3, 2018 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tinkertrain/741dcc95b1a4a7c8389d8cea2593f2f5 to your computer and use it in GitHub Desktop.
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
/**
* 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