Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /********************************************************************************************/
  2. /* Recursive function to flatten all nested elements of an array. */
  3. /* */
  4. /* - Each recursive iteration returns a new the flatered array with all its nested levels. */
  5. /* - The flattened array is built by a plain concatenation of each return callback. */
  6. /* */
  7. /* Example: [[1,2,[3]],4].get_flattened_array(); */
  8. /********************************************************************************************/
  9. Array.prototype.get_flattened_array = function() {
  10. var nested_array = this;
  11. var flattened_array = []; // Current level flattened array
  12.  
  13. try {
  14. for (var index = 0; index < nested_array.length; index++) {
  15. if (nested_array[index] !== null && nested_array[index].constructor === Array) {
  16. // If the element is an array, get its flattened array and concat it to the curren level flattened array
  17. flattened_array = flattened_array.concat( nested_array[index].get_flattened_array() );
  18. } else {
  19. // If it is not an array, just push it
  20. flattened_array.push(nested_array[index]);
  21. }
  22. }
  23. } catch(err) {
  24. console.log('Error in get_flattened_array: ' + err + ', with nested_array = ' + nested_array);
  25. } finally {
  26. return flattened_array;
  27. }
  28.  
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement