How can a function work with an array of subarrays of objects without altering the original array?

Within a small coding project I recently completed, I handled an array consisting of 3 subarrays, with each subarray containing 4 objects. I passed this array through a function that gradually removes values from each subarray until only 1 object remains in each one. Ultimately, the function returns an object holding the last remaining 3 objects.

However, an issue arises as the original array is being altered during this process, regardless of my attempts to prevent it. I tested various methods, such as:

    var itemsArr = [[obj1, obj2, obj3, obj4], [moreObj1, moreObj2, moreObj3, moreObj4],[lastObj1, lastObj2, lastObj3, lastObj4]];

    // each item in itemsArr subarrays represents objects with name, url, and id keys.

        var generateResults = function(array, num){
        var arr = array.slice();    // creating a copy of the original array here (though it's not functioning as expected)
// have also attempted arr = [].concat(array);
        var counter = 1;
        var holderObj;
        var results = {
          baby: null,
          husband: null,
          home: null
        };
        var tempArr;
        // iterate over the outer array, which contains arrays within each element
        var i = 0;
        while (true){
            if (arr[i].length === 1){
                holderObj = arr.splice(i,1)[0][0];
                i--; // adjusting for the reindexing of arr. alternatively, can iterate backwards if needed
                results[holderObj.id] = holderObj;
            }
            if (arr[i]){
                for (var j=0; j<arr[i].length; j++){
                    if (counter === num){
                        arr[i].splice(j,1);
                        counter = 0;
                        j--;  // accommodating the reindexing of arr[i]. Could also iterate in reverse
                    }
                    else{
                        counter ++;
                    }
                }
            }
            if (results.baby !== null && results.husband !== null && results.home !== null){
              break;
            }
            else if (i === arr.length-1){
                i = -1;
            }

            i++;
        }
        return results;
    }

How can I prevent the original itemsArr from undergoing modifications when calling generateResults(itemsArr, num)?

I've also experimented with replacing the initial line of generateResults with var arr = [].concat(array);

Answer №1

Consider implementing the Array.prototype.slice() method

generateResults(updatedItems.slice(), count)

var updatedItems = [{x:5},{y:6},{z:7},{w:8}];
var copiedItems = updatedItems.slice();
copiedItems.splice(2,1);
console.log(updatedItems, copiedItems);

Answer №2

To ensure that the array of arrays array parameter is not modified, it is recommended to create a two-level array copy by following these steps:

var arr = [];
// ...
for(var i = 0; i < array.length; ++i)
    arr[i] = array[i].slice();

By making a copy of array using the above method, both arr and array will be separate Array objects while maintaining the same elements. Therefore, any modifications made to arr[i] will not affect array[i].

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

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

Toggle the font weight in a text area by clicking a button

I need help with creating a button that will change the font-weight to bold when clicked and then revert back to normal when un-clicked. However, I only want the specific part of the text area where the user clicks the button to be bolded, not the entire t ...

Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with: function toggleTable(){ document.getElementById ...

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

Using jQuery for Dragging and Dropping Elements within Dynamically Loaded Divs with

Is it possible to drag an element on the page into a droppable element inside an ajax loaded div? The code works fine when the droppable element is placed directly in the regular page, but not within the ajax loaded div. It seems like the issue may be rela ...

How do I create individual tables for each JSON array within my object using React and MaterialUI?

I have a unique challenge with a component that creates multiple tables, all within one <TableContainer>. The issue lies in the fact that every table is confined within the same container and I am unable to customize each table separately. Each tabl ...

D3: Ensuring Map is Scaled Correctly and Oriented Correctly

I am attempting to integrate a map into a website using D3 and topoJSON that resembles the following: https://i.sstatic.net/1brVx.png However, when I create the map with D3/topoJSON, it shows up small and inverted. https://i.sstatic.net/LgQBd.png Even ...

Preventing commits when encountering build or lint errors

Every git repository contains git hooks within the .git/hooks directory. I have included a npm run lint command in the pre-commit git hook. However, I am unable to prevent the commit if npm run lint returns an error. ...

Calculate the total sum of selected values in a multiple select dropdown using jQuery

Is there a way to calculate the sum of selected items in a multiple selection dropdown menu? For instance, if I select "X12SO" and "X13SO", their values should add up to 30. let total = 0; $("select[name='myselect[]'] option").each(function(){ ...

Is it possible to use multiple routes in the same page with Vue-router?

In the process of developing a Vue-based web application that utilizes vue-router in history mode, everything was functioning smoothly for navigating between various pages. However, a new request has been made to open certain pages within a virtual dialogu ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...

What is the purpose of the "modal-backdrop fade show" element remaining visible after the associated component is unmounted, and what is the best way to eliminate or disable this div?

Scenario I have a Vue component that includes a child component responsible for displaying a modal. Toggling the isShowModal boolean either through a button click or Vue devtools successfully displays and hides the modal as expected. However, upon tryin ...

Error: The if statement is not providing a valid output

I am currently developing a basic price calculator that calculates the total area based on user input fields. While most of the program is functioning correctly, I am encountering an issue with the if statement that is supposed to determine the price rat ...

What is the best way to incorporate a dropdown menu into existing code without causing any disruption?

I've come across this question multiple times before, but I still haven't found a suitable answer or solution that matches my specific situation. (If you know of one, please share the link with me!) My goal is to create a basic dropdown menu wit ...

The dichotomy between public and private methods within a Vue.js component

Within a component, I have two functions defined. One is foo(), which is defined within <script>, and the other is fooExported(), which is defined in the body of export default {}. My understanding is that functions inside export default {} can be a ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

Animation issue in Material UI autocomplete label feature

Hello, I am currently delving into the world of React and Material UI. I have been working on implementing the Material UI auto complete feature with chip functionality. You can see my progress here: https://codesandbox.io/s/runh6. Everything seems to be w ...

Using two modal popups while passing an identifier

UPDATE: In my investigation, I discovered that a plain input tag without MVC RAZOR works as expected: <input type="text" class="hiddenid2" /> //WORKED However, when using the following code, it does not work: @Html.Editor("id", "", new { htmlAtt ...

Utilizing Google's GeoApi to retrieve users' location data regarding their city and country

I am currently using this code to retrieve the full address information of users function getGeo() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (a) { $("#geoLoc").html("Determining your location. ...