How to Flatten an Array in JavaScript

Using recursion and a while loop is on of the easier ways to do that

export default function flatten(value) {
const arr = []

const flat = (a) => {
let counter = 0
console.log(a)
while (counter < a.length) {
const val = a…


This content originally appeared on DEV Community and was authored by Rafael Thayto

Using recursion and a while loop is on of the easier ways to do that

export default function flatten(value) {
  const arr = []

  const flat = (a) => {
    let counter = 0
    console.log(a)
    while (counter < a.length) {
      const val = a[counter]
      if (Array.isArray(val)) {
        return flat(val)
      } else {
        arr.push(val)
      }
      counter++
    }
  }
  flat(value)
  return arr
}

You also can do that using a reduce() and array.concat()

export default function flatten(value) {
  return value.reduce((acc, val) => 
    Array.isArray(val)
      ? acc.concat(flatten(val))
      : acc.concat(val),
  []);
}


This content originally appeared on DEV Community and was authored by Rafael Thayto


Print Share Comment Cite Upload Translate Updates
APA

Rafael Thayto | Sciencx (2024-09-20T02:02:35+00:00) How to Flatten an Array in JavaScript. Retrieved from https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/

MLA
" » How to Flatten an Array in JavaScript." Rafael Thayto | Sciencx - Friday September 20, 2024, https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/
HARVARD
Rafael Thayto | Sciencx Friday September 20, 2024 » How to Flatten an Array in JavaScript., viewed ,<https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/>
VANCOUVER
Rafael Thayto | Sciencx - » How to Flatten an Array in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/
CHICAGO
" » How to Flatten an Array in JavaScript." Rafael Thayto | Sciencx - Accessed . https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/
IEEE
" » How to Flatten an Array in JavaScript." Rafael Thayto | Sciencx [Online]. Available: https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/. [Accessed: ]
rf:citation
» How to Flatten an Array in JavaScript | Rafael Thayto | Sciencx | https://www.scien.cx/2024/09/20/how-to-flatten-an-array-in-javascript-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.