Languages
[Edit]
EN

TypeScript - reverse array

0 points
Created by:
evangeline
420

In this article, we would like to show how to reverse an array in TypeScript.

Quick solution:

const array: string[] = ['a', 'b', 'c'];
const reversedArray: string[] = array.reverse();

const display = (array: string[]): void => {
  console.log(array.join(' '));
};

display(array);         // c b a   <------  Pay attention or use copy !!!
display(reversedArray); // c b a

Note: be careful reversing array because reverse() method works on source array obcject. It is safe to call array.slice().reverse().

Safe reversion example

When we use array in another place of application it is safe to use source array copy.

const array: string[] = ['a', 'b', 'c'];
const reversedArray: string[] = array.slice().reverse();

const display = (array: string[]): void => {
  console.log(array.join(' '));
};

display(array);         // a b c
display(reversedArray); // c b a

Output:

a b c
c b a

Array map() method example

In 2009, ES5 introduced Array.prototype.map() method that lets us write quick reversion logic with an arrow function.

const array: string[] = ['a', 'b', 'c'];
const reversedArray: string[] = array.map(
  (item: string, index: number, array: string[]) => array[array.length - 1 - index]
);

const display = (array: string[]): void => {
  console.log(array.join(' '));
};

display(array);         // a b c
display(reversedArray); // c b a

Output:

a b c
c b a
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join