📘
snesjhon
  • You Should Know
  • Personal
    • Blogs
      • I'll never complain about web tooling again.
      • vscodevim
  • JavaScript
    • Closures
      • Closure Q1
    • Values
      • Primitive vs Reference
      • Accessing by value and reference
    • Function
      • call, apply, bind
      • Pass by value
      • Different types of Scopes
      • Context vs Scope
      • Parse Time Vs Run Time
    • Hosting
      • Are Let & Const Hoisted?
      • Hoisting Q1
      • Hoisting Q2
    • Standard Objects
      • Math
        • Math.log10
        • Math.pow()
    • Array
      • Apply
      • Slice vs Splice vs Split
    • This
      • This - Q1
    • TypeScript
      • as const
    • FAQs
      • Modulo Operator
      • Timeout
      • Declarative vs Imperative
      • ++i vs. i++
    • Interview Questions
  • react
    • FAQs
  • Ruby
    • Debugging
    • Symbols
    • Intro
  • Algorithms
    • Sliding Window
      • minSubArrayLen
      • maxSubArraySum
      • findLongestSubstring
    • Frequency Counter
      • sameFrequency
    • Recursion
      • nestedEvenSum
      • flatten
      • Reverse a String
      • Fibonnacci
    • Searching
      • overlappingIntervals
      • twoStringSearch
      • binarySearch
    • Sort - Elementary
      • Selection Sort
      • Bubble Sort
      • Insertion Sort
      • quickSort
    • Sort - Intermediate
      • Radix Sort
      • Merge Sort
    • FAQs
  • Data Structures
    • Breadth First Search
    • Linked Lists
      • Singly Linked Lists
    • FAQs
  • Code Challenges
    • LeetCode
      • removeDuplicates
    • Hacker Rank
      • twoSums
      • Sock Merchant
    • Hacker Rank - Medium
      • New Year Chaos
  • Databases
    • SQL
Powered by GitBook
On this page
  1. Algorithms
  2. Recursion

flatten

Write a recursive function called flatten which accepts an array of arrays and returns a new array with all of the values flattened

flatten([1, 2, 3, [4, 5] ]) // [1, 2, 3, 4, 5]
flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5]
flatten([[1],[2],[3]]) // [1,2,3]
flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]) // [1,2,3
function flatten(arr) {
  if (arr.length < 1) return arr;
  if (Array.isArray(arr[0])) return flatten(arr[0]).concat(flatten(arr.slice(1)));
  return [arr[0]].concat(flatten(arr.slice(1)));
}
function flatten(oldArr){
  var newArr = []
    for(var i = 0; i < oldArr.length; i++){
      if(Array.isArray(oldArr[i])){
            newArr = newArr.concat(flatten(oldArr[i]))
      } else {
            newArr.push(oldArr[i])
      }
  } 
  return newArr;
}

Last updated 4 years ago