Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Different approaches to reverse an array
/* Case #1 - Notice that this example also mutates the original array. */
console.time('Test 1');
const arrayOne = [1, 2, 3, 4];
const newArrayOne = arrayOne.reverse();
console.log(arrayOne); // [ 4, 3, 2, 1 ]
console.log(newArrayOne); // [ 4, 3, 2, 1 ]
console.timeEnd('Test 1');
/* Case #2 */
console.time('Test 2');
const arrayTwo = [1, 2, 3, 4];
const newArrayTwo = arrayTwo.slice().reverse();
console.log(arrayTwo);
console.log(newArrayTwo);
console.timeEnd('Test 2');
/* Case #3 - Using 'spread' and 'reverse' */
console.time('Test 3');
const arrayThree = [1, 2, 3, 4];
const newArrayThree = [...arrayThree].reverse();
console.log(arrayThree);
console.log(newArrayThree);
console.timeEnd('Test 3');
/* Case #4 - Using 'forEach' and 'unshift' */
console.time('Test 4');
const arrayFour = [1, 2, 3, 4];
const newArrayFour: number[] = [];
arrayFour.forEach(item => {
newArrayFour.unshift(item);
});
console.log(arrayFour);
console.log(newArrayFour);
console.timeEnd('Test 4');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment