To iterate over an array in TypeScript in reverse order, you can use a for
loop starting from the last index to the first index.
In this example,
numbers
with some values.for
loop starting from the last index to iterate over each element of the array in reverse order.const numbers: number[] = [1, 2, 3, 4, 5];
for (let i = numbers.length - 1; i >= 0; i--) {
console.log(numbers[i]);
}
5 4 3 2 1
In this example,
fruits
with some values.forEach
method with an arrow function to iterate over each element of the array in reverse order.const fruits: string[] = ['apple', 'banana', 'cherry'];
fruits.reverse().forEach((fruit: string) => {
console.log(fruit);
});
cherry banana apple
In this tutorial, we learned How to Iterate Over an Array in Reverse Order in TypeScript language with well detailed examples.