In order to achieve reversing an array in JS without the reverse method, you can use a combination of a for loop or an array push method.
Let's take a look at this example:
Write a function, reverseArray(), that takes in an array as an argument and returns a new array with the elements in the reverse order.
function reverseArray(arr) {
const output = new Array;
for(let i = arr.length-1; i >= 0; i--) {
output.push(arr[i]);
}
return output;
}
//uncomment the code below to test in your IDE:
//const sentence = ['sense.','make', 'all', 'will', 'This'];
//console.log(reverseArray(sentence))
//Expected output:
'This', 'will', 'all', 'make', 'sense.' ]
This example is one of the most popular entry level interview questions for Javascript. I hope to solve more questions like this and also use this piece as a reference when needed. That will be all from me today. Until next time, remember to stay positive.
Food for Thought: “The point is not how we use a tool, but how it uses us.” ― Nick Joaquín
HAPPY CODING!!! ❤️
Add your comment