Learn JavaScript
❯ arrays.array_extras

flat, concat, reverse & More in JavaScript

$concept

Beyond the big five live the specialists: flat(depth) and flatMap flatten nesting (one level by default, Infinity for full), concat merges without mutating (spread usually reads better now), reverse sorts in place (copy first!), join stringifies with separators, and keys/values/entries yield iteration helpers.

ES2023 adds non-mutating trio toSorted/toReversed/with for immutable pipelines. Fill and copyWithin handle bulk initialization and shifting. The pattern across all: know which mutate (reverse, sort, splice) versus return fresh (map, filter, slice, flat).

$how it works
1

flat flattens nesting

[1, [2, [3]]].flat(2) β†’ [1, 2, 3] β€” depth-controlled, Infinity for arbitrary depth.

2

flatMap maps then flattens

One level of flattening fused with mapping β€” splitting sentences to words in a single pass.

3

reverse mutates

arr.reverse() flips in place β€” [...arr].reverse() or toReversed() when the original must survive.

4

Know mutating vs pure

Mutators: sort, reverse, splice, fill, copyWithin. Pure: map, filter, slice, flat, concat, toSorted.

$example
let nested = [1, [2, 3]];
console.log(nested.flat());
let words = ["hi there", "yo"];
console.log(words.flatMap((s) => s.split(" ")));
Output
[ 1, 2, 3 ]
[ 'hi', 'there', 'yo' ]
1flat() with default depth 1 dissolves one nesting level.
2flatMap splits each sentence then flattens β€” tokenizing in one method.
3Both print flattened β€” nesting handled declaratively.
$use cases
Flattening nested API responses with flat(Infinity)
Tokenizing with split-plus-flatMap pipelines
Non-mutating reversal via spread or toReversed()
Auditing mutating vs pure calls during review

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.