Skip to content

Instantly share code, notes, and snippets.

@longebane
Last active March 15, 2019 22:32
Show Gist options
  • Save longebane/834c28c7ccecc6fbda0ae74487b3ceb5 to your computer and use it in GitHub Desktop.
Save longebane/834c28c7ccecc6fbda0ae74487b3ceb5 to your computer and use it in GitHub Desktop.
Flatten Array
const arr = [[1,2,[3]],4];

let flatArr = flatten(arr);

/////////
function flatten(arr) {
  //reduce = we will iterate over the array, checking each element if it is an array, and will concat it into a final array
  return arr.reduce( (a,b) => {
    if (Array.isArray(b)) {
      return a.concat(flatten(b))
    }
    return a.concat(b)
  }, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment