Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active February 4, 2018 20:19
Show Gist options
  • Save mayashavin/1b1cec3497f0e9bf5ba709e82c957f7b to your computer and use it in GitHub Desktop.
Save mayashavin/1b1cec3497f0e9bf5ba709e82c957f7b to your computer and use it in GitHub Desktop.
function FlattenArray(arr){
var flattened = [];
while(arr.length){
var element = arr.pop(); //start from end
//if (element instanceof Array)
//if (Object.prototype.toString.call(element) === '[object Array]')
if (Array.isArray(element)){
arr = arr.concat(element);
}
else{
flattened.push(element);
}
}
return flattened.reverse();
}
function FlattenArray(arr){
var flattened = [];
for (var i = 0; i < arr.length; i++){
var element = arr[i];
if (Array.isArray(element)){
flattened = flattened.concat(FlattenArray(element));
}
else{
flattened.push(element);
}
}
return flattened;
}
function FlattenArray(arr){
var reducer = (flatten, original) => flatten.concat((Array.isArray(original) ? FlattenArray(original) : original));
return arr.reduce(reducer, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment