The Problem:
At the company I work for, we interview for front-end developer positions quite frequently. One of my coworkers always asked the interviewee how to reverse an array in JavaScript. Just for fun, I decided to to take on the challenge since .net makes it too easy (array.Reverse()).
Originally, my answer to the question was this:
My coworker said my solution would definitely work, but he then asked how I can improve the answer by saving on memory.
What I learned:
I didn't know how to improve the answer until I learned about JavaScript's splice method. Here's my improved script using splice:
With splice, as I'm moving an array value to the temp array, I'm completely removing the value and index from stringArray. In other words, as temp is growing, stringArray is shrinking. Eventually, stringArray will be empty. This method of reversing an array is a better solution than my original.
Further reading:
http://davidwalsh.name/remove-item-array-javascript
At the company I work for, we interview for front-end developer positions quite frequently. One of my coworkers always asked the interviewee how to reverse an array in JavaScript. Just for fun, I decided to to take on the challenge since .net makes it too easy (array.Reverse()).
Originally, my answer to the question was this:
var stringArray = [" Joey!", " Is", " Name", "my", " Hello,"];
var temp = new Array();
for(i = 0; i < stringArray.length; i++)
temp.push(actual[(stringArray. length - 1) - i]);
console.log(temp);
My coworker said my solution would definitely work, but he then asked how I can improve the answer by saving on memory.
What I learned:
I didn't know how to improve the answer until I learned about JavaScript's splice method. Here's my improved script using splice:
var stringArray = [" Joey!", " Is", " Name", "my", " Hello,"];
var temp = new Array();
while(stringArray.length)
temp.push(stringArray.splice(-1, 1)[0]);
console.log(temp);
With splice, as I'm moving an array value to the temp array, I'm completely removing the value and index from stringArray. In other words, as temp is growing, stringArray is shrinking. Eventually, stringArray will be empty. This method of reversing an array is a better solution than my original.
Further reading:
http://davidwalsh.name/remove-item-array-javascript
Comments
Post a Comment