← 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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (5)
expect(flatten([1, [2, [3, [4]], 5]])).toEqual([1, 2, 3, 4, 5]);
expect(flatten([[], [[]], 1])).toEqual([1]);
expect(flatten(["a", ["b"], { c: [1] }])).toEqual(["a", "b", { c: [1] }]);
expect(flatten([])).toEqual([]);
const source = [1, [2]]; flatten(source); expect(source).toEqual([1, [2]]);