Skip to content

Instantly share code, notes, and snippets.

@thedgbrt
Created February 2, 2017 00:05
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 thedgbrt/2f49478cfc494966b05d346e28028f7a to your computer and use it in GitHub Desktop.
Save thedgbrt/2f49478cfc494966b05d346e28028f7a to your computer and use it in GitHub Desktop.
JS flatten array
function flatten(arr){
var flatArr = [];
var recursive = function(arr2) {
if(arr2.length == 0) {
return;
} else if (Array.isArray(arr2[0])) {
recursive(arr2[0]);
} else {
flatArr.push(arr2[0]);
}
recursive(arr2.slice(1));
}
recursive(arr);
return flatArr;
}
var test1 = JSON.stringify(flatten([])) === JSON.stringify([]);
var test2 = JSON.stringify(flatten([1])) === JSON.stringify([1]);
var test3 = JSON.stringify(flatten([[1,2]])) === JSON.stringify([1,2]);
var test4 = JSON.stringify(flatten([[1,2],3])) === JSON.stringify([1,2,3]);
var test5 = JSON.stringify(flatten([[1,2,[3]],4])) === JSON.stringify([1,2,3,4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment