Making a surface-level copy of an array containing nested arrays

I am facing an issue with manipulating child arrays within a parent array. Specifically, I want to manipulate the first element in the first child array without affecting the rest of the arrays. However, my current code is shifting the first elements of all child arrays instead of just the first one.

After some investigation, I suspect that the problem lies in the fact that fillWith is being deep-copied. I have tried various methods to make it a shallow copy but haven't been successful.

What am I overlooking?

let arr= Array(3)        
let fillWith = Array.from({length: 5}, (_, i) => i+1);

arr.fill([...[], ...fillWith]) // Try 1
//arr.fill(fillWith.slice()) // Try 2


console.log(arr) // -> [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

arr[0].shift();

console.log(arr)
/* 
How I want it to be -> [[2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
What it actually becomes -> [[2, 3, 4, 5], [2, 3, 4, 5], [2, 3, 4, 5]]
*/

Answer №1

Here is one way to accomplish it:

const fillArray = () => Array.from({length: 5}, (_, index) => index + 1);

const newArray = Array.from({length: 3}, fillArray)

console.log(JSON.stringify(newArray))

newArray[0].shift();

console.log(JSON.stringify(newArray))

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

Looking to center a title in React Navigation without interference from headerLeft?

I am using react navigation and trying to center the title in the header bar. However, it seems to be affected by the presence of headerLeft. When I disable headerLeft, the title centers perfectly. How can I achieve this without interference from other lef ...

Display the specific outcome solely from an array using AJAX

I possess an array of objects in JSON format as shown below: [{"id":"0","NameInData":"","name":"","type":"mf","greeting":"Bonjour","message":"GENERIC: Lorem ipsum."}, {"id":"1","NameInData":"alexis","name":"Alexis","type":"mf","greeting":"Bonjour Alexis", ...

Having trouble sending data to an API through jQuery: the function is not functioning properly

Currently, I am in the process of developing an HTML form that allows users to input values into text fields and submit them to an external API called ThingSpeak. This API then uses the received values to generate a plot displayed within an iframe. Althoug ...

Game where two players take turns playing against each other

I'm facing a bit of a dilemma at the moment. I am in the process of creating a simple turn-based two-player game, and I have been experimenting with Node.js and Socket.IO based on recommendations from a question I found: Multiplayer JavaScript game ...

angularjs Populate input fields with default values within ng-repeat loop

Our challenge is to display input text with pre-filled values within a list using the ng-repeat directive. <ul ng-repeat="post in postList> <input type="text" ng-model="postid" nginit="postid='{{post.id}}'"></input> </u ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

How to make a div in Javascript smoothly slide out when it appears

Looking to add some smooth sliding animation to this basic JS code instead of the glitchy appearance it currently has. I've experimented with different options but haven't had any success, any suggestions? Here's the code snippet along with ...

Using Jquery to generate key value pairs from a form that is submitted dynamically

I'm still learning the ropes of jquery and struggling with a specific issue. I'm looking for a way to dynamically set key:value pairs in the code below based on form inputs that have variable values. The code works when I manually add the key:va ...

Constructing a table using an array in React

I need assistance with creating a table based on salary data for different sectors. I have an array with example data that includes currencies and sectors. const data=[ ['Euro','Tech'], ['USD','Tech'], ['GBX&apo ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...

"Exploring the world of Material UI styling with ReactJS: A deep dive

I've been busy developing a small web application using ReactJS and Material UI. In the documentation examples, many components include useStyles within the code. I've decided to follow suit and now have a useStyles function in each of my compone ...

Execute button click automatically upon page loading in AngularJS

I'm trying to figure out how to automatically trigger a button click on an AngularJS page when the page loads based on a querystring value. In a traditional asp.net web forms page, I could easily handle this scenario by calling Button1_Click(sender,e) ...

Transform the JSON format received from the API endpoint to make it suitable for use in the component

I'm working on a react-native app that fetches event data from a wordpress endpoint. Below is the JSON I receive from the wordpress API. How can I restructure it to fit into my calendar component? Where should I handle this restructuring in my app? ...

Styling text using CSS depending on the displayed text

Utilizing Awesome Tables (AT), I am extracting data from a Google Sheets document to display on a website. The HTML template in the sheets is used for formatting the data, specifically focusing on the table output with inline CSS styling. Since the templat ...

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...

"Encountering a challenge when trying to populate a partial view using AngularJs and MVC

I am a beginner in AngularJS and I'm using a partial view for Create and Edit operations, but I'm encountering issues while trying to retrieve the data. The data is successfully being retrieved from my MVC controller but it's not populating ...

Is there a way to incorporate a Gif into the background of a three.js project?

function initializeGame() { cubeSize = 200; fieldDepth = 50; fieldWidth = 200; fieldHeight = 200; initObstacles = _ => _; // set the game size var WIDTH = 1000; var HEIGHT = 500; // set camera properties var VIEW_ANGLE = 40, ...

Error in JSON data structure while transferring data from Jquery to PHP

Having some trouble with my first attempt at sending a JQuery request to an API I'm developing. My PHP code keeps reporting that the JSON is malformed. Interestingly, if I create a JSON array in PHP and send it through, everything works perfectly. Bu ...

Refresh the Vue component in a single-page application project

As I develop a spa app using vue js, I have set up these routes: { path: '/artikel/create',name: 'artikelCreate', components: { default: artikel_form, 'header': header} }, { path: '/artikel/edit/:id',name: 'art ...