← All tasksJavaScript · Junior

flatten: flatten a nested array

Write a function flatten(array) that turns an array of any nesting depth into a flat one. Leave objects alone: only arrays get flattened.

Try to solve it without Array.prototype.flat, as interviewers usually ask.

Tests (5)

  1. expect(flatten([1, [2, [3, [4]], 5]])).toEqual([1, 2, 3, 4, 5]);
  2. expect(flatten([[], [[]], 1])).toEqual([1]);
  3. expect(flatten(["a", ["b"], { c: [1] }])).toEqual(["a", "b", { c: [1] }]);
  4. expect(flatten([])).toEqual([]);
  5. const source = [1, [2]];
    flatten(source);
    expect(source).toEqual([1, [2]]);