Guest User

Untitled

a guest
Apr 24th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. // Arbitrarily nested array
  2. let arr = [[[[1,2],[[3,3],4],5,6]],7];
  3. // Final array that would contain the flattened elements
  4. let flattenedArray = [];
  5.  
  6. /*
  7. * @function flatten
  8. *
  9. * @args element element to be flattened or passed back to recursion
  10. *
  11. * @description if the element is an array pass each of elements to this function.
  12. * When the element is not an array , push this element to the flattened array
  13. *
  14. * @output flattenedArray contains the flattened form of the initial arbitrarily sized array
  15. */
  16. function flatten(element) {
  17. if (element.constructor === Array) {
  18. for (let idx = 0; idx < element.length; idx++) {
  19. flatten(element[idx]);
  20. }
  21. } else {
  22. flattenedArray.push(element);
  23. }
  24. }
  25.  
  26. // Call the function with the main array as the argument
  27. flatten(arr);
  28.  
  29. // Print the final flattened array (output)
  30. console.log(flattenedArray);
Add Comment
Please, Sign In to add comment