Created
August 1, 2020 18:56
-
-
Save martingaido/a4046e5c23cfe620e106d3e9559b4820 to your computer and use it in GitHub Desktop.
Different approaches to reverse an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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