Skip to content

Instantly share code, notes, and snippets.

@AlexandrFadeev
Last active September 12, 2017 05:10
Show Gist options
  • Save AlexandrFadeev/0ba17d104501eacf46bac64da3ed4afc to your computer and use it in GitHub Desktop.
Save AlexandrFadeev/0ba17d104501eacf46bac64da3ed4afc to your computer and use it in GitHub Desktop.
Flatten array algorithm in javascript
/**
Convert nested array to flat array
*/
function flattenArray(arr) {
/**
Create en empty array. In this array we will push elements from nested array passed
as a parameter.
*/
var flatArray = [];
/**
Iterate through array in classic 'for' loop.
*/
for (var i = 0; i < arr.length; i++) {
/**
check if the current element of array is an instanse of 'Array' type.
If so, we call this function again (recursion) and pass as a parameter
array which was at index 'i' if original passed array...
*/
if (arr[i] instanceof Array) {
/**
Create constant that holds result of nested array. In our case nested array is
value at index 'i' in passed 'arr' array
*/
const recursionResult = flattenArray(arr[i]);
/**
iterate through array (nested) of element 'i' and push elements of this array to
array created earlear ('flatArray')
*/
for (var j = 0; j < recursionResult.length; j++) {
flatArray.push(recursionResult[j]);
}
} else {
/**
Adds element of passed array to 'flatArray'
*/
flatArray.push(arr[i]);
}
}
/**
returns flat array
*/
return flatArray;
}
/**
Usage
*/
const nestedArray = [1, 2, 3, [4, 5], [6, [5, 0]], 44, ["some string", [[10, 11], [12, 13]], 4.9]];
console.log(flattenArray(nestedArray));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment