2

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
  • 26,400
  • 25
  • 118
  • 202
  • 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

6

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
  • 230,986
  • 31
  • 415
  • 357