Reputation: 27536
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
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