EN
TypeScript - reverse array
0 points
In this article, we would like to show how to reverse an array in TypeScript.
Quick solution:
xxxxxxxxxx
1
const array: string[] = ['a', 'b', 'c'];
2
const reversedArray: string[] = array.reverse();
3
4
const display = (array: string[]): void => {
5
console.log(array.join(' '));
6
};
7
8
display(array); // c b a <------ Pay attention or use copy !!!
9
display(reversedArray); // c b a
Note: be careful reversing array because
reverse()
method works on source array obcject. It is safe to callarray.slice().reverse()
.
When we use array in another place of application it is safe to use source array copy.
xxxxxxxxxx
1
const array: string[] = ['a', 'b', 'c'];
2
const reversedArray: string[] = array.slice().reverse();
3
4
const display = (array: string[]): void => {
5
console.log(array.join(' '));
6
};
7
8
display(array); // a b c
9
display(reversedArray); // c b a
Output:
xxxxxxxxxx
1
a b c
2
c b a
In 2009, ES5 introduced Array.prototype.map()
method that lets us write quick reversion logic with an arrow function.
xxxxxxxxxx
1
const array: string[] = ['a', 'b', 'c'];
2
const reversedArray: string[] = array.map(
3
(item: string, index: number, array: string[]) => array[array.length - 1 - index]
4
);
5
6
const display = (array: string[]): void => {
7
console.log(array.join(' '));
8
};
9
10
display(array); // a b c
11
display(reversedArray); // c b a
Output:
xxxxxxxxxx
1
a b c
2
c b a