Skip to content

Instantly share code, notes, and snippets.

@daviseford
Created January 6, 2017 02:10
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 daviseford/d552467dab998e2cbb03f80331351d6e to your computer and use it in GitHub Desktop.
Save daviseford/d552467dab998e2cbb03f80331351d6e to your computer and use it in GitHub Desktop.
Flatten arrays of arbitrary depths, bringing all integers to top level
'use strict';
function flatten(array) {
let result = [];
const f = function (x) {
if (Array.isArray(x)) {
x.forEach((x) => { f(x) });
} else if (typeof x === 'number') {
result.push(x)
}
};
f(array);
return result;
}
assert flatten([]) === []
assert flatten([[[[[[[[[[[[[[1]]]]]]]]]]]]]]) === [1]
assert flatten([[[3],[[[6,9]]]]]) === [3,6,9]
assert flatten([[4,5,'a','b'],[],[[[0]]]]) === [4,5,0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment