Gary McGill
Gary McGill

Reputation: 27536

How to get a reversed ReadonlyArray?

If I have a ReadonlyArray<T> and I want to obtain another ReadonlyArray<T> with the same items but in reverse order, what's the easiest way to achieve that?

For example:

const scoresInAscendingOrder: ReadonlyArray<number> = [1, 2, 3, 5, 9];
const scoresInDescendingOrder: ReadonlyArray<number> =  ???;

I can't use scoresInAscendingOrder.reverse() because ReadonlyArray does not support that method (and rightly so since it would modify scoresInAscendingOrder).

Upvotes: 2

Views: 1477

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250056

You can just use slice and reverse the result of that:

const scoresInAscendingOrder: ReadonlyArray<number> = [1, 2, 3, 5, 9];
const scoresInDescendingOrder: ReadonlyArray<number> = scoresInAscendingOrder.slice(0).reverse()

Or you can use the newer spread syntax:

const scoresInDescendingOrder: ReadonlyArray<number> = [...scoresInAscendingOrder].reverse()

Upvotes: 6

Related Questions