Which method flattens nested arrays to a specified depth?

The story behind the answer

Which method flattens nested arrays to a specified depth? The answer is flat().

Array.prototype.flat() creates a new array by removing nested array levels up to the depth supplied as its argument. Calling values.flat(1) removes one layer; values.flat(2) removes two. With no argument, the default depth is 1. Passing Infinity recursively flattens all reachable array nesting, although a finite depth is usually clearer and safer.

The method was standardized in ECMAScript 2019. It does not mutate the original array, which distinguishes it from mutating methods such as splice(). Elements that are empty slots in sparse arrays can also disappear during flattening. Non-array values are copied as elements, while arrays are expanded according to the requested depth.

A frequent mistake is to write flatten(), but that is not the standard JavaScript Array method. reduce() can be used to build a custom flattening routine, but it does not flatten arrays by itself. flatMap() is a related method: it maps each element and then flattens the result by exactly one level, making it useful when transformation and flattening belong in the same operation.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: