Last active
September 22, 2016 06:29
-
-
Save thysultan/0d3fd1d225d0ab3f3aa44395f8d7db98 to your computer and use it in GitHub Desktop.
flatten array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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