Reversing an array in JavaScript without using extra memory allocation

Currently, I'm working on a code challenge to reverse an array in place without using the reverse function while learning Javascript from Eloquent JavaScript.

function reverseArrayInPlace(arr) {
   for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[(arr.length - 1) - i];
  }

  return arr;
}

After writing the above code, I encountered an issue where the reversal didn't work as intended due to reassigning values. For example, when I tried

reverseArrayInPlace([1, 2, 3, 4 ,5])
, it returned [5, 4, 3, 4, 5].

Here's the suggested solution:

function reverseArrayInPlace(array) {
  for (let i = 0; i < Math.floor(array.length / 2); i++) {
    let old = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = old;
  }
  return array;
}

I would appreciate it if someone could explain the solution and how it works so that I can gain a better understanding. Thank you :)

Answer №1

Let's dissect the inner workings of this particular function:

for(let i = 0; i < Math.floor(array.length / 2); i++)
:

The Math.floor() function is utilized here to ensure that the loop only iterates through half of the array. This prevents the original issue of duplicating elements instead of reversing them.

let old = array[i]:

This line introduces a temporary variable to store the element at the current index during the swap process.

array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = old;

These lines are responsible for swapping the elements within the array.

Finally, there is only return array; left to complete the function.

Answer №2

To optimize the swapping process, it is advisable to loop over only half of the array. This helps prevent redundant swaps that may not affect the overall array. Instead of transposing two values, simply copy over the value at the reflected index in each iteration. This avoids the need for a temporary variable to store one of the values.

Answer №3

If you have an array like [1, 2, 3, 4, 5], the process begins by swapping the leftmost element with the rightmost element, resulting in [5, 2, 3, 4, 1]. This swapping continues with each subsequent element, moving towards the middle of the array. The use of Math.floor(array.length) ensures that elements that have already been swapped are not swapped again, limiting the operation to only the first half of the array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: Adding element to array failed due to index being out of array bounds

In my current project, I have an array where I append new options. These options are then displayed in a table that consists of 3 sections. The first two sections each have only one row, while the third section can have a variable number of rows depending ...

I am looking to include query string variables within JSON key-value pairs

On my webpage, I have a .asp page using the following url: page.asp?id=33&album=ourcookout The page.asp file then calls a file.js script. Within the file.js script, there is a line located under a function that reads as follows: url: "post_file.php", M ...

Ways to retrieve data values from one class to another in React

My current challenge involves creating a search bar that filters a dataset using a search function with multiple states. Initially, the search function worked well when the search bar and results page were in the same class. However, I am now trying to sep ...

Sketch a line extending from one element to the next

Is there a way to create a styled line that starts from the center of one <td> element and ends at the center of another? I attempted to use the jQuery Connections plugin but it only connects the edges of the elements, not their centers. The plugin ...

Using Jquery and Ajax to pass an extra PHP variable to a server-side script

I am working with a dropdown select box where the selected option is sent to a server-side script using Ajax. <select id="main_select"> <option selected="selected" value="50">50</option> <option ...

What is the process for adding JSON data to a dropdown menu using PHP AJAX?

I am trying to populate a select html element with data from a list of JSON results. Here is the code I have attempted: JSON output: jquery loop on Json data using $.each {"Eua":"Eua","Ha'apai":"Ha'apai",& ...

Utilizing Ajax in conjunction with Ruby on Rails

I have a question that may be quite basic (I am new to Rails 3). I am looking to implement Ajax functionality where once a user clicks on a link, it triggers a $.post call and initiates some server-side changes. Within the _share partial file, I currently ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Sending values to server-side function with JavaScript

Is there a way to invoke a code-behind function from JavaScript and pass parameters to it? For instance: <script> var name; <% createUser(name) %> </script> private void createUser(string Name) { // Do some complex operations } I&a ...

Another exciting discussion on converting JSON to an HTML table

While I know that asking a question without providing any code is generally discouraged, I am feeling quite lost at the moment. I have some basic JSON files that follow a structure similar to the example below: [{ "key1" : "some value", "key2" : 1 ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

Is it better to set the language of Puppeteer's Chromium browser or utilize Apify proxy?

Looking to scrape a website for French results, but the site supports multiple languages. How can I achieve this? Is it best to configure Puppeteer Crawler launch options using args, like so: const pptr = require("puppeteer"); (async () => { const b ...

How to parse JSON data (coming from a Socket.io response) in Unity

When I retrieve data from the web server in json format, I am unable to deserialize it and access the keys (e.g., first_name). The client receives the information, but the code fails to print anything in the Unity console. Here is my code: socket.On("Us ...

The NextJs router encountered an unknown key passed through the urlObject during the push operation

I have a Next.js/React application where I am utilizing the Next Router to include some queries in my URL. However, when using the following function, the Chrome Dev Console displays numerous warnings: const putTargetsToQueryParams = (targets: IFragrance ...

How can I apply various textures in three.js?

Hello there! I'm diving into the world of threejs and currently working on a block game similar to Minecraft. Instead of relying solely on objects, I've decided to build my program using planes (specifically the PlaneGeometry class). As I wrap ...

Differences between CookieParser and req.cookies in ExpressJS

As I was reading the documentation on req.cookies in expressjs docs, I learned that when the cookieParser() middleware is used, this object defaults to {} but otherwise contains the cookies sent by the user-agent. Then, exploring the details of the Coo ...

Why won't Node.js let me redirect to my error page?

I've been putting together my newsletter project with the Mailchimp API, everything seems to be working fine except for when I try to redirect to a failure page if the status code is not 200. The browser shows an error message saying 'localhost r ...

I struggled to modify the image cropping code to specify a particular image

(I will attempt to explain my issue once again) I came across a script online which can be viewed at this link : Link However, I am having trouble modifying the code to suit my needs. The script currently starts working on image upload, but I want it t ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...