Contrasting Results When Reversing an Array

Currently, I am delving into my Javascript book and attempting to master the art of reversing an array by creating a custom reverse function. My challenge is to flip the array without resorting to creating a new variable for storage. After what seemed like finding the solution, running output tests in two different ways (refer below) resulted in contrasting results:

function reverseArrayInPlace(array) {
  for (var i = 0; i < array.length; i += 1) {
    array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
  }
  console.log(array);
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

The outputs are as follows:

reverseArrayInPlace(array);
console.log(array);
> [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
> [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Interestingly, I realize that utilizing console.log() inside the function returns the intended result.

However, when I utilize console.log() outside the function, it inexplicably causes the original array configuration with the last element omitted. An explanation regarding this peculiar behavior would be greatly appreciated.

Answer №1

The array within the function exists within its own scope separate from the global / window level. The global array remains untouched; instead, the function modifies a local copy of it.

If you fail to pass array as an argument to the function, it would affect the globally defined array variable:

function reverseArrayInPlace() { // <-- no parameter
  for (var i = 0; i < array.length; i += 1) {
    array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
  }
  console.log(array);
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
reverseArrayInPlace();
console.log(array);

(...though it is generally discouraged to rely on globals in this manner because of the risk of inadvertently masking them with local variables, as demonstrated here. A more recommended approach is for functions to accept data as parameters and return values, allowing you to assign the returned value as needed when calling the function.)

Answer №2

When working inside the reverseArrayInPlace function, you are actually reassigning the variable for the array, rather than mutating it. This means that the original array you pass in remains unchanged. The console.log statement inside the function will show the modified array, while the one outside will display the original array.

If you're looking for a different approach, consider using the following code instead:

function reverseArrayInPlace(array) {
  for (var i = 0; i < array.length; i += 1){
    array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
  }
  return array;
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var newArray = reverseArrayInPlace(array)

console.log(newArray)

Answer №3

Approaching the array reversal process in a unique way, this method involves utilizing a function stack to store array items. The approach includes popping the value, checking the array length, recursively calling the function with the same object reference, and then unshifting the temporarily stored value back into the array.

It's worth noting that while this method may be useful for educational purposes or for small arrays, its reliance on the stack means it may not be suitable for larger datasets due to limitations on stack size.

function reverseArrayInPlace(array) {
    var temp = array.pop();
    if (array.length) {
        reverseArrayInPlace(array);
    }
    array.unshift(temp);
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

reverseArrayInPlace(array);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

Within the initial loop of your for statement, you are utilizing array.pop() to alter the array provided as an argument. However, afterwards, you are creating a new array and storing it in the same variable, causing the original array's reference to be lost. As a result, the subsequent loops generate the modified array within your function.

To address this issue, I have included a line of code that copies the original array instead of modifying the original argument.

function reverseArrayInPlace(array) {
array = array.slice(); // making a copy of the original array
for (var i = 0; i < array.length; i += 1) {
array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
}
console.log(array);
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

reverseArrayInPlace(array);
console.log(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

Is it possible for jQuery UI Dialog to function similar to an iFrame?

Is there a way to set up my dialog box with a form so that when the form is submitted, only the dialog box changes instead of the browser location? ...

Tips for implementing i18n translation for a specific text variable in Vuejs

Typically, we simply assign the translation property to a variable like : this.name = this.$t('language.name'); However, there may be cases where we want to specify it in a specific language (e.g. French). Is there a way to achieve this in vue.j ...

What is the method for obtaining the 'value' and inserting it into the class name "scroll_box"?

function Following(){ follow_render().then((value)=>{ console.log(value) }); return( <div className="Following"> <div className="Following_box_flex"> <div className="Following_box"> ...

What is the best way to enable onClick events for individual elements within a .map() function?

I am currently building a chat application and need to display a list of users in the chat. Each user should have a button that, when clicked, opens a menu allowing admins to ban that specific user. However, I am facing an issue where clicking on the &apos ...

Utilize Vuex store in Vue without the need for import statements within components

When working with Vue 2/3 and in an ES6 environment, I often access a Vuex store in an external JS file using the following method: // example.js import { store } from '../store/index'; console.log(store.state.currentUser); While this method w ...

Finding it difficult to switch between routes while utilizing tabs in an Ionic Vue application

Although I have experience as a front-end developer, I am new to Ionic and may ask some basic questions. Currently, I am using Ionic-Vue to develop a mobile app. Initially, I started with the tabs default template which allows me to switch between tabs se ...

Encountered an error 'Unexpected token ;' while attempting to include a PHP variable in a jQuery AJAX call

Trying to execute a PHP script that updates a deleted field in the database when you drag a specific text element to a droppable area. Currently, here is the droppable area code: <div class="dropbin" id="dropbin" > <span class="fa fa-trash-o ...

Use AJAX to send the form instead of using the action attribute

Struggling to get a form to submit using ajax instead of an action attribute, but so far, nothing seems to be working. The PHP script functions correctly when tested with an action submit. I've researched examples, read documentation, asked questions ...

Encountering problem when trying to upload several images at once using a single input in CodeIgniter with

I'm attempting to use CodeIgniter and AJAX to upload multiple images using a single input field. Here's the code I have so far: HTML: <input type="file" name="files[]" id="file" multiple /> AJAX: $("#addItems").on("submit",function(e) { ...

Obtaining a value from a function in JavaScript

Hey there, I'm having an issue with the code snippet below. It's not returning 'baz' correctly and instead shows that it's undefined. Any idea why this is happening? getJSON = function(options, onResult) { //console.log("rest: ...

An elementary comparison inquiry involving JavaScript string manipulation

Encountering an issue with string comparison while working on Node.js and its included crypto module for signature verification of incoming data. Here is the code snippet: console.log(` SIG : '${signature}' - type: ${typeof signature} HASH : & ...

What is the best way to show database information when the route is updated?

I'm currently developing a chat application using vue.js and firebase. My goal is to retrieve certain data from the database based on the route ID and display it on the screen whenever there is a route change. However, I have encountered unexpected be ...

What is the best way to display today's date using JavaScript?

echo '<script>alert('.date('Y-m-d H:i:s').')</script>'; Seeking advice as a novice, I attempted to display the current date and time using the code above without success. Can anyone provide guidance on how to achi ...

transferring data from config file (conf.js) to a grunt task or sharing information between different grunt

Is there a way to transfer data between different grunt tasks? I need to send a value from one grunt task to another grunt task. In my case, I want to pass a value to a new grunt task after running a protractor test. I attempted to store the value in proc ...

Navigating a sortable list using jQuery

I have integrated the "sortable" script from on my web application to create a sortable list of items. While the sorting functionality works perfectly, I now need to update my server with the new order whenever changes are made. To capture the sorting ev ...

How can data be shared between two functional child components in a React application?

I've been researching on Google quite a bit on how to transfer props between functional components, but it seems like there isn't much information available (or maybe I'm not using the right keywords). I don't need Redux or globally st ...

Transform Python SQL data into an array format resembling a CSV

Hello there, I am currently facing a challenge with reading my SQL data into an array in Python. As I am relatively new to Python, any guidance would be greatly appreciated! ...

Launching the file explorer when the icon is clicked

I am currently working with Angular 5 using Typescript. I need assistance in opening the file explorer window to add an attachment when clicking on an icon. I have successfully done this for a button, but I am facing issues with the click event binding on ...

Is the confirmation window not showing up on the active tab in Chrome Extension? It only seems to appear on the popup.html tab

I have created a Chrome extension for an e-gym that is designed to prompt a confirm window after every hour of using the Chrome browser. The issue I am facing is that the confirm window only appears on popup.html. I want to activate my extension so that it ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...