How to create a flat version of a deeply nested array? [Programming Interview Question]
@Yomesh Gupta

JavaScriptAll Levels
4140
Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.

InternationalDomestic

Given a deeply nested array, create a function on the array, namely flatten, that when invoked returns a flat version of the original array. Function should be defined in a way that it can be invoked on existing and future arrays.

Demo:

var input = [
  1, 2, 3,
   [4],
  [5, 6, [7], [8, [9, [10]]]],
  11, 12, 13,
  [14, [[[[[15, [16]]]]]]],
  17, 18,
  [19, [20, [21, [22, [23, [24, [[[[[25]]]]]]]]]]]
 ];
  
var flatArray = input.flatten();
 // flatArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

Loading IDE...