Aller au contenu principal

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

remarque

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"]