Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Last active April 26, 2023 14:03
Show Gist options
  • Select an option

  • Save adeleke5140/d8d3aa254d27d8620675cd39a312b9a6 to your computer and use it in GitHub Desktop.

Select an option

Save adeleke5140/d8d3aa254d27d8620675cd39a312b9a6 to your computer and use it in GitHub Desktop.
Flatten a multidimensional array

Flatten an array

With recursion

The recursive approach is concise but there is the concern of overflowing the call stack. That can be solved with a generator.

With iteration

An iterative approach is also good to know

We loop through the array with a while loop and we take out an item from the array one at a time to check to see if that item is an array. If the item is not an array, we put it into the res array. If it is an array, we use a spread operator ... to get all the items out of it and put them back to the array. using Array.prototype.some

function flatten(value){
//do this immutably without modifying the initial arr
value.reduce((acc, cur) => acc.concat(Array.isArray(curr) ? flatten(curr): curr), [])
}
//iteration
function flatten(value){
const res = []
const copy = value.slice()
while(copy.length){
const item = copy.shift()
if(Array.isArray(item)){
copy.unshift(...item)
}else{
res.push(item)
}
}
return res
}
//written more concisely
function flatten(value){
while(value.some(Array.isArray)){
value = [].concat(...value)
}
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment