Skip to content

Instantly share code, notes, and snippets.

@thysultan
Last active September 22, 2016 06:29
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 thysultan/0d3fd1d225d0ab3f3aa44395f8d7db98 to your computer and use it in GitHub Desktop.
Save thysultan/0d3fd1d225d0ab3f3aa44395f8d7db98 to your computer and use it in GitHub Desktop.
flatten array
/**
* flattens a nested array
* 1. takes an array and optional destination array
* 2. iterates through the array
* 3. if an item in the array is an array
* run through flatten with the second argument
* as the destination array
* this will add every item within the passed array
* into the destination array
* return the new flat array
* @param {Array} arr - input array
* @param {Array}? flatArr - optional output array address
* @return {Array} flatArr - output array
*/
function flatten (arr, flatArr) {
flatArr = flatArr || [];
var length = arr.length|0;
for (var index = 0; index < length; index = index + 1){
var item = arr[index];
item.constructor === Array ? flatten(item, flatArr) : flatArr[flatArr.length] = item;
}
return flatArr;
}
console.log(flatten([[1,2,[3]],4]));
// http://jsbin.com/yeyolo/edit?js,console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment