Skip to content

Instantly share code, notes, and snippets.

@heroqu
Last active June 7, 2016 16:28
Show Gist options
  • Save heroqu/2b56532791a84c49790edc33a8e10952 to your computer and use it in GitHub Desktop.
Save heroqu/2b56532791a84c49790edc33a8e10952 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
'use strict'
/**
* flatten an array of arbitrarily nested arrays of integers into a flat array of integers
*/
function flat_numeric_arr(x, res) {
res = res || [];
if (typeof x === 'number') {
res.push(x);
} else if (Array.isArray(x)) {
x.forEach((y) => {
flat_numeric_arr(y, res);
})
} else {
// throw 'improper argument type'; // ok, just ignore for now
}
return res;
}
// let a = [1,2,[3, 4], 'w', 5,[[6,7,8], 9, 10]];
// let b = flat_numeric_arr(a);
// console.log(b); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment