Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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