Answers for "how to flatten array in javascript using foreach loop"

0

how to flatten array in javascript using foreach loop

function flatten(arr) {
  const result = []

  arr.forEach((i) => {
    if (Array.isArray(i)) {
      result.push(...flatten(i))
    } else {
      result.push(i)
    }
  })
  
  return result
}

// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]

flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Posted by: Guest on July-22-2020

Code answers related to "how to flatten array in javascript using foreach loop"

Code answers related to "Javascript"

Browse Popular Code Answers by Language