how to flatten array in javascript using foreach loop

Solutions on MaxInterview for how to flatten array in javascript using foreach loop by the best coders in the world

showing results for - "how to flatten array in javascript using foreach loop"
Pia
15 Jun 2019
1function flatten(arr) {
2  const result = []
3
4  arr.forEach((i) => {
5    if (Array.isArray(i)) {
6      result.push(...flatten(i))
7    } else {
8      result.push(i)
9    }
10  })
11  
12  return result
13}
14
15// Usage
16const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
17
18flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
19