EN
TypeScript - reverse array
0
points
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 callarray.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