Reverse an array

You know there is array.reverse() function, sharing the snippet below just in case wondering how to do it. We iterate half of the lentgh, guess why?

let array = [1, 2, 3, 'Siesta', 5, 6, 7, 7, 'Spain'];
for (let i = 0; i < array.length / 2; i++) {
    let val= array[i];
    array[i] = array[array.length - i - 1];
    array[array.length - i - 1] = val;
}
console.log(array);

#array #typescript #javascript

Advertisements