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 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.
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.
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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With