What causes alterations in a single cell to spread to adjacent cells within this 2D array initialized using the fill function?

I seem to be encountering an issue with this 2-dimensional array in JavaScript. It appears that when I modify a[1][0], the value of a[0][0] also changes. Could it be a problem with how I am initializing it? If so, what is the correct way to initialize it to avoid this issue?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Answer №1

var a = Array(100).fill(Array(100).fill(false));

The variable a is an array where each element references another array filled with false values. By filling the outer array with references to the same inner array, any changes made to one element will affect all elements because they are pointing to the same array.

This can be rewritten as:

var a1 = Array(100).fill(false);
var a = Array(100).fill(a1);

In this version, the variable a contains 100 elements that all reference the same array a1. Therefore, changing one element in a will result in changes across all elements since they share the same array.

If you want each element in the outer array to have its own separate array, you can achieve this by:

var a = [];
for(var i=0; i<100; i++)
  a.push(Array(100).fill(false));

Answer №2

Your array will contain references to the same (second dimension) array object throughout.

If you want each element to hold distinct objects, you can achieve that with the following approach:

const a = Array(100).fill(false).map(x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);

It's crucial to initialize the values in the initial array to something (like false in this scenario), as the constructor creates a sparse array and the map() function only works on existing properties.

To overcome this limitation, you could utilize Array.from():

const a = Array.from(Array(100), x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);

Answer №3

The issue arises from utilizing the second Array(100).fill(false) in every index of the first array. This causes a problem where modifying one value in the "second" dimension affects all positions in the array. To resolve this, you need to generate a new Array for each position within the initial array.

var x = Array(100).fill().map(x => Array(100).fill(false));

Answer №4

Here you are essentially populating a larger array with the same array object at each index.

Instead of:

Array(x).fill(Array(y).fill(false));

You should do:

Array(x).fill(Y); // This will fill X with Y

If you modify Y, the same value will be reflected in every index of X.

It is recommended to use a loop when filling data that is an object (remember, an Array is also an object).

Answer №5

At first glance, this may seem like a repeated question, but my go-to solution has always been the following:

let matrix = new Array(10).fill(false).map(() => new Array(10).fill(false));
matrix[5][5] = true;

Source: How can I create a two dimensional array in JavaScript?

Answer №6

When it comes to creating an N Dimensional array in JavaScript, it's not as simple due to arrays being reference types. To achieve this, you'll need to first create a clone tool.

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};

function createNDArray(...dimensions){
  return dimensions.reduceRight((prev, current) => current = (new Array(current)).fill().map(e => Array.isArray(prev) ? prev.clone() : prev ));
}

var newArray = createNDArray(2,3,4,"x")
console.log(JSON.stringify(newArray));

The createNDArray function takes any number of integer arguments, each specifying the size of a dimension, with the last argument representing the fill value.

Answer №7

The mdn explains the fill function as copying the same value to all array indices. By utilizing a specific utility, it becomes possible to generate clones of the array. However, the use of the slice operator restricts this action to only cloning arrays.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

if (!Array.prototype.duplicateFill) {
  Object.defineProperty(Array.prototype, 'duplicateFill', {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var arr = Object(this);

      // Steps 3-5.
      var length = arr.length >>> 0;

      // Steps 6-7.
      var startingIndex = arguments[1];
      var relativeStartIndex = startingIndex >> 0;

      // Step 8.
      var k = relativeStartIndex < 0 ?
        Math.max(length + relativeStartIndex, 0) :
        Math.min(relativeStartIndex, length);

      // Steps 9-10.
      var endingIndex = arguments[2];
      var relativeEndIndex = endingIndex === undefined ?
        length : endingIndex >> 0;

      // Step 11.
      var finalIndex = relativeEndIndex < 0 ?
        Math.max(length + relativeEndIndex, 0) :
        Math.min(relativeEndIndex, length);

      // Step 12.
      while (k < finalIndex) {
        arr[k] = value.slice(0);
        k++;
      }

      // Step 13.
      return arr;
    }
  });
}
Array(100).duplicateFill(Array(100))
a[0][0] = true
a[1][0]
false

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

Receive characteristics in component specification

Is there a way to pass the native attributes of an img element to a custom image component without explicitly defining each one, like alt, and have them all be applied to the img tag? Here is an example of what I mean: @Component({ selector: 'image ...

Scrolling triggers the click event

Within my JavaScript code, I have a rather simple event listener set up to listen for a click: element.addeventlistener('click', ()=>{ #do somthing }) However, I am encountering an issue on IOS (iPhone) where scrolling triggers the event list ...

Does AngularJS's scope.$apply function operate synchronously?

Can you confirm if this code is synchronous in AngularJS? scope.$apply(function(){ console.log('foo'); }); ...

What steps should I take to address the issue with my navbar?

I've written some code that creates a hamburger icon on mobile devices. When the user clicks it, a wave effect covers the screen, but I'm facing an issue where the wave doesn't cover the input field. My query is: how can I make the input fi ...

What is the best way to transfer information to a different NextJS page?

I want to implement a search input field. The idea is to allow the user to type something into the search bar and then send that input to another page where an API request will be made with the search content. Essentially, when the user types "something" ...

The radio button fails to trigger the setState function in React

In my React program, I have implemented a method to update the state and modify a specific value for a Radio button: The state : class App extends Component { constructor(props) { super(props); this.state = { checked: [], expanded: [], ...

Extracting necessary data from a JSON file and generating a new JSON file with the selected information

My task involves parsing a JSON file to extract events that fall within a specified start and end time provided via an HTTP GET request. The goal is to return these filtered events as a new JSON-encoded response. Despite brainstorming two potential solutio ...

Is it possible to achieve the full image when utilizing double buffering for drawing on canvas?

I have a code where I am using two canvas elements to draw an image in order to prevent flickering. However, I am facing an issue where I cannot get the full image to display when using this method. When I use just one canvas, the image displays fine. It ...

Using Javascript to hide specific rows in a table

Question for Javascript beginners: I am aware that there are numerous ways to achieve this task, many of which are explained on various platforms. However, my question pertains specifically to the following code snippet. <html> <head> <scri ...

Does Three.js come with a default function for generating heightmaps?

Currently, I am engrossed in developing a JavaScript game using Three.js. My interest lies in enhancing the realism of the walls by incorporating a height map (refer to the provided image). View this snapshot of the game design featuring a 2D wall. All th ...

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

Resetting Tabs in Child Component using React

Imagine having two intricate React components developed in TypeScript where one acts as a child component of the other. This child component consists of tabs and keeps track of its own state to determine which tab is currently selected: export const Clien ...

Display the values of the returned array in PHP using the print_r function

I am attempting to utilize a date function that I found on a popular coding website to generate an array of dates between two specified dates. This is the function: function createDateRangeArray($strDateFrom,$strDateTo) { // takes two dates in the forma ...

Implementing a Scalable Application with React Redux, Thunk, and Saga

What sets Redux-Saga apart from Redux-Thunk? Can you explain the primary use of redux saga? What exactly is the objective of redux thunk? ...

Vue TypeError: Object(...) function not recognized

I am currently learning Vue and experimenting with form handling. I am developing a web application for managing meetings which includes a multi-step form to collect visitor and host data. However, upon clicking the submit button, I encounter the following ...

Utilizing JavaScript to exchange "unprocessed" Apple Events on OS X (El Capitan)

I'm exploring the new JavaScript Automation feature in OS X (10.11) to automate a specific application that lacks a dictionary. My current approach involves using AppleScript with raw Apple Events as follows: tell application "Bookends" return «ev ...

I am encountering the error message "array.sh: 3: array.sh: Syntax error: "(" unexpected"

I just created this code snippet: #!/bin/bash #Simple array array=(1 2 3 4 5) echo ${array[*]} Unfortunately, I encountered an error message while running it: array.sh: 3: array.sh: Syntax error: "(" unexpected After doing some research on Google, ...

storing a hashed value within an array in Ruby

I am currently facing an issue with inserting a list of account numbers into an array from a JSON response. I have successfully converted the JSON return into a hash, but encountered difficulties while trying to store the values in an array. When checking ...

The issue arises when AngularJS binding to a JSON object results in the value being

I am encountering a complex problem with nested bindings in custom directives. The JSON structure I am working with resembles the following; { survey: questions:[ { text:'Question 1', answers:[ { ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...