Flatten One Level

easy
By FrontendAtlas Editorial · Updated Nov 22, 2026
This should not deep-flatten; only the first nesting level is removed, matching Array.prototype.flat(1). Use it to normalize API data; edge cases include sparse arrays and mixed types. Performance should stay linear, and tests should ensure order is preserved.

Arguments

  • arr: any[] — The input array which may contain nested arrays.

Returns

any[] — A new array shallow-flattened by one level.

Solution idea

Because only one level is flattened, you can implement it with a single pass and no recursion while preserving order and immutability.

Examples
// Basic example
flattenOnce([1, [2, 3], [4, [5]]]) // => [1, 2, 3, 4, [5]]

// Already flat
flattenOnce([1, 2, 3]) // => [1, 2, 3]

// Mixed values
flattenOnce([[1], 2, [3, [4]], 5]) // => [1, 2, 3, [4], 5]

// Sparse array: holes are skipped, as flat(1) skips them
flattenOnce([1, , [2, , 3]]) // => [1, 2, 3]

Public interview reports

These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.

Reported in a public Meta interview account. Meta frontend interview questions

Reported in a public Shopee interview account. Shopee frontend interview questions

Reported in a public Anduril interview account. Anduril frontend interview questions

Reported in a public Binance interview account. Binance frontend interview questions