Reputation: 495
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?
Upvotes: 10
Views: 8319
Reputation: 813
There are already a lot of answers but maybe someone find this one more readable:
let rows = 3;
let columns = 5;
let rowTemplate = Array(columns).fill(false);
let matrix = Array.from(Array(rows), () => [...rowTemplate]);
matrix[1][3] = true;
/*
[
[ false, false, false, false, false ],
[ false, false, false, true, false ],
[ false, false, false, false, false ]
]
*/
Upvotes: 1
Reputation: 368
Quite similar to Ori Drori answer, but a little bit shorter :
const rows = 3;
const cols = 5;
const nestedArray = Array.from({length: rows}, () => Array(cols).fill(false));
nestedArray[1][2] = true;
console.log(nestedArray);
Upvotes: 1
Reputation: 690
Maybe something like:
const rows = 3
const cols = 5
const nestedArray = new Array(rows).fill(0);
nestedArray.forEach((e, i, a) => a[i] = new Array(cols).fill(false));
console.log(nestedArray);
Upvotes: 0
Reputation: 129
const nestedArray = Array(rows).fill(false).map(x => Array(cols).fill(false))
try this one
Upvotes: 0
Reputation: 122135
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)
Upvotes: 5
Reputation: 193130
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);
Upvotes: 10