Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a two-dimensional array in JavaScript

I would like to create a two-dimensional array that gets initialized with booleans which are set to false. Currently I'm using this method of array creation:

const rows = 3
const cols = 5

const nestedArray = new Array(rows).fill(
    new Array(cols).fill(false)
)

The nestedArray looks fine, but as soon as I change the value of nestedArray[0][2], the values of nestedArray[1][2] and nestedArray[2][2] also get changed.

I guess this is because the sub-arrays are identical, probably because they get filled into the parent array by reference and not by value.

What would be an elegant and efficient way of creating an array of non-identical sub-arrays instead?

like image 863
lsgng Avatar asked Apr 24 '18 13:04

lsgng


People also ask

How do you initialize a two-dimensional array?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.

Are there 2D arrays in JavaScript?

The Concept of Jagged Arrays Technically, there is no two-dimensional array in JavaScript. JavaScript supports 2D arrays through jagged arrays – an array of arrays. Jagged arrays are essentially multiple arrays jagged together to form a multidimensional array.

How do you initiate an array in JavaScript?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


2 Answers

You can use nested Array.from() calls:

const rows = 3
const cols = 5

const nestedArray = Array.from({ length: rows }, () => 
  Array.from({ length: cols }, () => false)
);
  
nestedArray[0][1] = 'value'; // example of changing a single cell
  
console.log(nestedArray);
like image 116
Ori Drori Avatar answered Nov 02 '22 05:11

Ori Drori


You could use Array.from method to create rows where second parameter is map method, and Array.fill for columns.

const rows = 3
const cols = 5

const nestedArray = Array.from(Array(rows), _ => Array(cols).fill(false));
nestedArray[0][1] = true;
console.log(nestedArray)

Another approach would be to use spread syntax ... on rows array so you can then use map method on that array.

const rows = 3
const cols = 5

const nestedArray = [...Array(rows)].map(_ => Array(cols).fill(false))
nestedArray[0][1] = true;
console.log(nestedArray)
like image 34
Nenad Vracar Avatar answered Nov 02 '22 07:11

Nenad Vracar