Creating an autonomous duplicate of a reversed array using JavaScript

Check out my code snippet here: http://jsfiddle.net/sepoto/Zgu9J/1/

I've started by creating a function that reverses an array:

function reverseArray(input) {
    var reversed = new Array;
    for(var i = input.length-1; i >= 0; i--) {
        reversed.push(input[i]);
    }

    //I attempted changing the return value to
    //return reversed.slice(0), but it did not create
    //an independent copy as intended
    return reversed;
}

The second array I created, pointOrigins2, is not truly independent of pointOrigins1. Any modifications made to pointOrigins2 are also reflected in pointOrigins1, which is not the desired behavior. Despite trying suggestions from StackOverflow such as using slice or a for loop, I have not been able to achieve the desired result yet, hence I created this fiddle.

Is there a way to produce an independent copy of the reversed array?

Answer №1

When creating a new independent array, ensure that you are also making independent copies of the items filling your arrays. To achieve this, consider the following approach:

function reverseArr(input) {
    var ret = new Array;
    for(var i = input.length-1; i >= 0; i--) {
        ret.push({
            positionx: input[i].positionx, 
            positiony: input[i].positiony, 
            index: input[i].index
        });
    }

    return ret;
}

This way, you will create new objects with identical properties in addition to the new array.

Answer №2

implement this algorithm

function reverseArrayElements(inputArr) {
var reversedArray = [];
for(var index = inputArr.length-1; index >= 0; index--) {
    reversedArray.push(inputArr[index]);
}
return reversedArray;
}

Answer №3

To easily reverse your array, make sure to clone it first!

The quickest method is:

var newArray = oldArray.slice();

Using concat works too. Here's an example:

Fastest way to duplicate an Array in Javascript - slice vs for loop

If slice doesn't create a copy for you, consider using numpy arrays and creating a deep copy like this:

np.copy(array);

For more information: http://documentationlink.com

Answer №4

const flipArray = (arr) => {
    return [...arr].reverse();
}

Answer №5

Your code is functioning correctly, though it could be shortened to

return input.slice().reverse();

//The following demonstrates that pointOrigins2 is not an independent copy of pointOrigins1
//Modifying pointOrigins2 also affects pointOrigins1
pointOrigins2[0].index++;

It's important to note that by modifying the pointOrigins2 array in this way, you are actually only altering the specific point object within both arrays. However, pointOrigins1 !== pointOrigins2.

If you want to modify one array independently from the other, you can do so like this

pointOrigins2[0] = {
    positionx: pointOrigins2[0].positionx, 
    positiony: pointOrigins2[0].positiony, 
    index:     pointOrigins2[0].index + 1
};

This ensures that pointOrigins1 remains unchanged. To have points with properties that can be modified without affecting other arrays, new points must be created.

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 necessary to specify a data type for the response when making an AJAX POST request?

After carefully reviewing my code, I have ensured that all the variables in my JavaScript match and are properly set up. Additionally, I have confirmed that all the variables in my data array for my AJAX request correspond correctly to my $_POST['var& ...

preg_replace_callback failing to retrieve the expected data

I previously asked about replacing named 'parameters' within a string in PHP on Stack Overflow. While the class used to function correctly, I'm encountering issues now that I'm trying to integrate it into the new Bolt CMS as an extensi ...

Best practices for server side countdown implementation

Issue I am facing a challenge with displaying a server-side countdown on the client side. Initially, I set it up using socket.io to emit data every 100 milliseconds. While I like this approach, I am concerned about potential performance issues. On the o ...

Generating a diagonal matrix using a set of matrices in MATLAB

I am wondering how to generate a diagonal matrix using an array of matrices. I have generated an array of matrices in MATLAB: X<62x62x1000> containing 1000 matrices with dimensions 62x62 My goal is to construct a matrix with dimensions 62000x62000 ...

Testing the update functionality of meta content in the Vue Quasar Meta component using Jest

I am currently working on unit testing the process of updating meta content for a Vue & Quasar page by utilizing the useMeta component offered by Quasar. My approach to testing this involves creating a mock Vue component called UseMetaComponent, which is ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Discover the process of incorporating two distinct component structures within a single React application

In my React app, I am trying to implement a different navbar for routes that start with "admin". For example: Normal Page: <NormalNavbar/> <NormalHeader/> <NormalBody/> <NormalFooter/> But if it's an admin route, then I want: ...

JavaScript function not executing

Within a panel in an UpdatePanel, there is both a dropdown list and a file upload control. The goal is to enable the Upload button when a value is selected from the dropdown and a file is uploaded. This functionality is achieved through a JavaScript functi ...

What is the best method for gathering information from multiple input fields?

I'm currently working on developing a Polymer application that includes a search button with multiple input boxes. I want the search operation to consider all the inputs from these boxes when performing a search. Here is an image depicting the scenar ...

The latest on rectAreaLight enhancements in three.js

It seems like this abandoned feature of three.js has become somewhat of a coveted prize; I've attempted to incorporate it a few times without success. You can find an example that works on an older release here: My minimal broken example is availabl ...

Automatically conceal a div or flash message after a short period of time by utilizing CSS3 in a React

I am relatively new to the React environment and recently created a basic component for a bookmarking feature. Essentially, when the favourite icon is clicked, an ajax call is sent > a record is created in the database > on ajax success, a flash me ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Unable to access current props within useEffect block

When I use useEffect with the parameter props.quizStep, my function fn (which is a keydown event listener) is unable to access the current value of props.quizStep. I'm puzzled as to why it's not working properly. Can you help me understand? Bel ...

The integration of a webview within an Ionic application

I have developed a mobile app using the Ionic framework and now I am trying to incorporate a webview using Chrome browser instead of the default browser. Initially, I used the cordova-plugin-inappbrowser plugin but found it to be unstable. I then tried t ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...

Displaying Google Street View and Google Maps with marker points in a parallel arrangement

Is there a way to align the Street View window with marker points from Google Maps? Here is the code that needs attention: <div id="property_map"></div> <script> /* Code for Google Map */ func ...

Error: Attempting to access properties of an undefined object (specifically 'query')

My productController.js const Product = require('../models/product'); const ErrorHandler = require('../utils/errorHandler'); const catchAsyncError = require('../middlewares/catchAsyncErrors'); const APIFeatures = require(&apo ...

Sending a collection of objects as a parameter in Android Java

Is there a way to send this data [{'name','abc'},{'call','cdf'}] as a JSON response in an Android app developed in Java? I know JSON.stringify can be used in JavaScript, but how can this be accomplished in the Androi ...

Leveraging jQuery to implement onclick functionality within a Jinja2 loop

I'm currently working with Python, Flask, and Jinja2. When using a for loop, I want to be able to click on the {{ place.place_photo }} element to toggle its details. Initially, I had it functioning correctly but ran into an issue where clicking on on ...