Instructions on utilizing Array.fill() with a single object but creating distinct copies for each index

When creating an array and populating it using the fill method, I noticed that changing array1[0].foo also changes all other objects in the array.

const array1 = Array(2).fill({ foo: null })
array1[0].foo = 'bar' // [ { foo: 'bar' }, { foo: 'bar' } ]

Is there a way to utilize the fill method while ensuring each index contains a unique copy of the same object?

Answer №1

Trying to implement Array#fill in this scenario won't yield the expected result as it uses a constant value.

An alternative approach would be to utilize Array.from, allowing you to map the object as needed.

const array = Array.from({ length: 2 }, _ => ({ foo: null }));

array[0].foo = 'bar';

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

Issue with Many to Many Relation Query in Objection JS, Postgres, and Express Resulting in 'TypeError: Cannot Read Property 'isPartial' of Null' Error

I have a challenge connecting the 'products' table to the 'tags' table using a many-to-many relationship structure with the 'products_tags' table. Upon executing const product = await Product.relatedQuery('tags').fi ...

What is the best way to change the status of a disabled bootstrap toggle switch?

I'm working with a read-only bootstrap toggle that is meant to show the current state of a system (either enabled or disabled). The goal is for it to update every time the getCall() function is called. However, even though the console logs the correct ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Incapable of modifying the inner content of a table

I am completely new to AngularJS and struggling with updating the inner HTML of a table. I have a variable that contains a string with three types of tags: strong, which works fine, and nested tr and td tags. However, when I try to replace the table's ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

"Enhance your website with a dynamic animated background using Bootstrap container

I'm struggling to understand why the Bootstrap container is blocking the particles-js animation behind the text. I want the background surrounding the text to be animated as well... :/ Example Code: .gradient-bg { background: rgba(120, 87, 158, ...

Locate the nearest upcoming date and time to today's date in the JSON response

I am currently working with an API that provides a response containing the `start_time` field in JSON format. My goal is to extract the ID from the JSON object whose next date time is closest to the current date and time, excluding any dates from the past. ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...

Displaying image titles when the source image cannot be located with the help of JavaScript or jQuery

I am currently facing an issue where I need to display the image title when the image is broken or cannot be found in the specified path. At the moment, I only have the options to either hide the image completely or replace it with a default image. $(&apo ...

Ways to address time discrepancies when the countdown skips ahead with each button click (or initiate a countdown reset upon each click)

Every time I click my countdown button, the timer runs normally once. But if I keep clicking it multiple times, it starts skipping time. Here are my codes: <input type="submit" value="Countdown" id="countdown" onclick="countdown_init()" /> <div i ...

Whenever I attempt to start the server using npm run server, I encounter the following error message: "Error: Unable to locate module './config/db'"

This is the server.jsx file I'm working with now: Take a look at my server.jsx file Also, here is the bd.jsx file located in the config folder: Check out the db.jsx file Let me show you the structure of my folders as well: Explore my folder structur ...

Image carousel with variable height

I'm attempting to implement a slide show of images with previous and next functionality. When the user clicks "previous," I want the images to slide to the left, and when they click "next," I want the images to slide to the right with a 0.5 second del ...

What is the most efficient way to transfer data to another page without having to repeatedly retrieve it from a

Looking for a way to pass additional data to another page when clicking on an item. I attempted to extend the father class to the child class, but it significantly slowed down the process due to the frequent class calls. This application is a dashboard w ...

Is there a way to retrieve consecutive rows from mysql_fetch_assoc() in a separate file and store them in an array variable?

I am currently working on creating a simple "list-out" feature for displaying places/spots within a city from a table. To achieve this, I have set up a Place class and implemented a "get" function that returns an array using mysql_fetch_assoc(). This setup ...

Is there a workaround using jQuery to enable CSS3 functionality across all browsers?

Is there a way in jQuery to make all browsers act as if they have CSS3 capabilities? ...

Sorting an array based on its keys is necessary

I'm a bit uncertain about how to approach this task. I have a set of values retrieved from a SQL query, presented in the following format: $row[0] = array('lid' => 1, 'llayout' => 1, 'lposition' => 1, 'mid& ...

Is there a way to determine the quantity of identical zero elements that match up in two numpy arrays?

Having two numpy arrays of the same size, each with values of 1, 0, and -1, I am able to count the number of matching ones and negative ones. However, I am unsure how to properly count the elements with the same index and a value of zero. I'm a bit p ...

I'm just starting to delve into React and I am eager to transform my regular JavaScript code into a React format. However, I am not quite sure how to

In my React JavaScript, I am trying to insert some regular JavaScript code. I attempted to use the {} brackets, but it did not work as expected. import './App.css'; function App() { return ( <> <div className=" ...

Issue with Angular ngFor not updating radio button value when ngModel is set

Hello, I am fairly new to working with Angular and could really use some assistance with a problem I've run into. Essentially, I am receiving an array of objects from an API like this: [{name: "abc", score: 2},{name: ""def, score: ...

Exploring the use of the map function for iterating in a stepper component of

I've been attempting to integrate Redux Form into my stepper component. However, I'm facing an issue where adding form fields results in them being displayed in all three sections. To address this, I started reviewing the code for the stepper. I ...