1

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).

Gary McGill
  • 25,192
  • 24
  • 113
  • 193
  • 3
    See [Reverse array in Javascript without mutating original array](https://stackoverflow.com/q/30610523/1715579) -- that question not about typescript but almost every answer there will also work here. – p.s.w.g Mar 19 '19 at 13:37

1 Answers1

5

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()
Titian Cernicova-Dragomir
  • 196,102
  • 20
  • 333
  • 303