Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. // [[1,2,[3]],4]
  2.  
  3. var arr = arrayFlatten([[1,2,[3]],4,[1,[2,[3]]]]);
  4. console.log(arr);
  5.  
  6. //Main function
  7. function arrayFlatten(obj){
  8. var flattenArray=[];
  9. //Call recursive funcion sending the array as "reference"
  10. flatten(obj,flattenArray);
  11. return flattenArray;
  12. }
  13.  
  14. function flatten(obj, flattenArray){
  15. //If is an array, go for each element and call the same recursive function
  16. if(isArray(obj)){
  17. obj.forEach(function(item){
  18. flatten(item,flattenArray);
  19. });
  20. }
  21. else{
  22. //is an integer, just push in the array
  23. flattenArray.push(obj);
  24. }
  25. }
  26.  
  27. function isArray(obj) {
  28. //Check if the object is an array
  29. return Object.prototype.toString.call(obj) === '[object Array]';
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement