Unexpected behavior observed with array value assignment in Javascript

I'm currently working on a code that involves assigning a value to a single cell in a 2-D array. However, the assignment isn't giving me the expected result.

let arr = new Array(3).fill(new Array(3).fill(0));
arr[1][1] = 1;
console.log(arr.toString());

It's puzzling why the output turns out this way.

The second code snippet below gives me the desired output, but I prefer achieving it in a way similar to the first example.

let arr = [];
for(let i = 0; i < 3; i++){
  arr.push([]);
  for(let j = 0; j < 3; j++){
    arr[i].push(0);
  }  
}
arr[1][1] = 1;
console.log(arr.toString());

Answer №1

If you want to ensure unique array references, consider using the convenient mapping callback provided by Array.from()

let newArray = Array.from({length:3}, (_,index) => Array(3).fill(index));

console.log(newArray)

Answer №2

Your initial approach creates a single array and fills all its elements with the same values. This means any changes made to one element will affect all others as well. If you want each element to have its own separate array, you can achieve this by using the map method:

let newArray = new Array(3).fill(null).map(_ => new Array(3).fill(0));
newArray[1][1] = 1;
console.log(newArray.toString());

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

Popover with Bootstrap 4 input field

The issue is outlined in the title. I am facing a problem where an input field loses focus within a Bootstrap 4 modal and popover setup, specifically in Firefox but not in IE 11. Popover: $('[data-toggle="popover"]').popover({ conta ...

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

Activating a function that requires locating a dynamically loaded element on the webpage using AJAX

I have a unique page on my website that allows users to make edits. Whenever they click on an item, the edit form is seamlessly loaded into a specialized section of the page using AJAX. Depending on the chosen item, the form fields are already prefilled w ...

PHP: Issue with properly removing empty values from an array using unset

I need help with breaking a string containing sentences into an array, modifying each array item, and removing any empty items. This is my current approach: //Split the string by dot $items_array = explode(".", $raw_data); //Iterate through the array fo ...

Tips for utilizing .env variables within npm scripts

I have set the following variable in my .env file: SHOPIFY_STORE_URL=mystore.myshopify.com Now, I am looking to utilize this variable in an npm script like so: "scripts": { "shopify-login": "shopify login --store=SHOPIFY_STO ...

Is it true that modifying an object will have consequences on an array once the object has been added to it?

Currently, I am working on coding in JavaScript using nodejs. My goal is to gather trading candle data into an object and then add that object to an array where I can manage and access multiple candles' worth of data. However, as a non-expert, I am e ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

jQuery validation rules are not functioning as they should

<script type="text/javascript"> $(document).ready(function () { $("#loginForm").validate({ rules: { email: { required: true, minlength: 10 }, ...

Retrieve the array that is passed back from a controller

After a user attempts to log in, my Laravel backend sends back a response. I need to extract and display this data in the front-end. How can I specifically isolate and target the errors that are included in the response? Currently, I am using the followi ...

Emphasize Links in Navigation Bar

I am in the final stages of completing the navigation for my website. I have included the jsfiddle code to display what I have so far. The issue I am facing is that my child links turn gray as intended, but I also want the top level link to turn gray when ...

Error encountered in AngularJS: Unexpected POST request

I am facing some challenges when trying to send an http post request to the server. I am using PhoneGap to develop an application that utilizes AngularJS. Can someone guide me on how to make a post request using AngularJS? Here is a snippet of my code: . ...

Why does the details page consistently receive the final item from the list?

For my e-commerce project built with React, I have a section to showcase featured items. Currently, there are only 9 items marked as featured in my database. Additionally, I am working on a modal details popup page that appears when you click on any item. ...

C++ sending back a specialized class as the return value of a function

It has been a while since I last dabbled in C++, and now I am attempting to write a concise function to parse a vector from a string formatted as "{(0.00, 0.00); (1.00, 0.00); (0.00, 1.00); (1.00, 1.00)}" into a custom class. Unfortunately, I am facing di ...

Loop through an array of objects that are in JSON format, make changes to them, and add new elements to them, all while utilizing

After pulling data from a database in JSON format and assigning it to the variable 'var tabs', here is how the formatted JSON looks: [{ "TAB_ID": "1", "TAB_NAME": "TAB ONE", "TAB_DISPLAY": "1", "QUESTIONS": [{ "QUESTION_I ...

Guide to obtaining specific top elements from an array using JavaScript

I'm seeking assistance with sorting arrays in JavaScript. Here is an example of a sorted array: mainArray : [25 20 20 20 18 17 17 15 12 12 10 5 5 ] The mainArray may contain duplicate values. A. Dealing with duplicates Based on user input, I need ...

Prevent the parent component's ripple effect from being activated by the child component

If I have a simple code snippet like the following: <ListItem button={true} > <Typography variant='caption' color='primary'> {value} </Typography> <Button onClick={foo} > Button ...

What is the best way to setup a function parameter to store responses from an inquirer.prompt inquiry using JavaScript and integrating with MySQL?

How can I incorporate function parameters to handle answers from an inquirer.prompt question in JavaScript? While I already know how to achieve this without using variables, I aim to enhance the usability of my addToTable function by utilizing parameters ...

Continuously encountering the "Uncaught Error: Bootstrap dropdown requires Popper.js" message despite having already added popper.js to the code

Recently beginning my journey with Angular and Bootstrap, I decided to create a simple "hello world" app. I've included all the necessary libraries, but I encountered an error that has me stuck. Error: Bootstrap dropdown requires Popper.js I' ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...