Skip to content

Instantly share code, notes, and snippets.

@martingaido
Created August 1, 2020 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martingaido/a4046e5c23cfe620e106d3e9559b4820 to your computer and use it in GitHub Desktop.
Save martingaido/a4046e5c23cfe620e106d3e9559b4820 to your computer and use it in GitHub Desktop.
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