Skip to main content

reverse()

reverse<T>(array): T[]

Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.

WHY WRAPPING NATIVE?

Unlike the native Array.reverse() which mutates the original array, this function returns a new array, preserving immutability. See Design Philosophy

note

For ES2023+, consider using Array.toReversed().


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: readonly T[]โ€‹

The array to reverse.


Returns: T[]โ€‹

A new array with elements in reverse order.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(n) time and space โ€” creates a shallow copy then reverses in place.


Also known asโ€‹

reverse (Lodash, es-toolkit, Remeda, Ramda, Effect) ยท โŒ (Radashi, Modern Dash, Antfu)


Exampleโ€‹

const numbers = [1, 2, 3, 4, 5];

const reversed = reverse(numbers);
console.log(reversed); // [5, 4, 3, 2, 1]
console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)

How it works?โ€‹

Reverses array order. Unlike native Array.reverse(), returns a new array (immutable).


Use Casesโ€‹

Display newest-first without mutating source ๐Ÿ“Œโ€‹

Reverse chronological data for UI display. Native array.reverse() mutates - this returns a new array safely.

const commits = ["Initial commit", "Add feature", "Fix bug", "Release v1.0"];

const newestFirst = reverse(commits);
// => ["Release v1.0", "Fix bug", "Add feature", "Initial commit"]

console.log(commits[0]);
// => "Initial commit" (original unchanged โœ…)

Toggle sort direction in data tablesโ€‹

Switch between ascending and descending views. Common pattern for sortable columns.

const prices = [19.99, 29.99, 49.99, 99.99];

const descending = reverse(prices);
// => [99.99, 49.99, 29.99, 19.99]

Process items in LIFO orderโ€‹

Handle stack-like structures without mutation. Useful for undo systems, breadcrumbs, or navigation history.

const breadcrumbs = ["Home", "Products", "Electronics", "Laptops"];

const backPath = reverse(breadcrumbs);
// => ["Laptops", "Electronics", "Products", "Home"]