jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
21 stars 4 forks source link

18 - flatten #23

Open jsartisan opened 4 months ago

jsartisan commented 4 months ago

index.js

export function flatten(arr, depth = 1) {
  return arr.reduce((acc, value) => {
    if (Array.isArray(value) && depth > 0) {
      acc = acc.concat(flatten(value, depth - 1))
    } else {
      acc.push(value)
    }

    return acc;
  }, [])
}