The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
Answer from Mohammed Ashfaq on Stack OverflowThe Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
This does the job in one line.
var A = Array(12).fill(null).map(()=>Array(81).fill('q'))
This is an array of references and a bad idea as harunurhan commented.
var A = Array(12).fill(Array(81).fill('q'));
Filling up a 2D array with random numbers in javascript - Stack Overflow
How can I create a two dimensional array in JavaScript? - Stack Overflow
How to create a two-dimensional array?
Why do 2d arrays behave differently when I create them using Array.fill() vs when I create them by iterating over the rows and columns?
You were thinking in the right direction but there are some errors in your code ;)
- You have to initialize the array first before you can push elements into it.
- And you were counting i++ twice
Javascript
var ground = []; // Initialize array
for (var i = 0 ; i < 15; i++) {
ground[i] = []; // Initialize inner array
for (var j = 0; j < 9; j++) { // i++ needs to be j++
ground[i][j] = (Math.random() * 5 | 0) + 6;
}
}
Maybe even better (reusable)
function createGround(width, height){
var result = [];
for (var i = 0 ; i < width; i++) {
result[i] = [];
for (var j = 0; j < height; j++) {
result[i][j] = (Math.random() * 5 | 0) + 6;
}
}
return result;
}
// Create a new ground with width = 15 & height = 9
var ground = createGround(15, 9);
Here's a quick example. I've created a function that will take in a width and height parameter and generate the size requested. Also I placed your tile function inside generate ground to keep it private, preventing other script from invoking it.
var ground = generateGround(10, 10); //Simple usage
function generateGround(height, width)
{
var ground = [];
for (var y = 0 ; y < height; y++)
{
ground[y] = [];
for (var x = 0; x < width; x++)
{
ground[y][x] = tile();
}
}
return ground;
function tile()
{
return (Math.random() * 5 | 0) + 6;
}
}
http://jsbin.com/sukoyute/1/edit
Here's a quick way I've found to make a two dimensional array.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(e => Array(y));
}
You can easily turn this function into an ES5 function as well.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(function(e) {
return Array(y);
});
}
Why this works: the new Array(n) constructor creates an object with a prototype of Array.prototype and then assigns the object's length, resulting in an unpopulated array. Due to its lack of actual members we can't run the Array.prototype.map function on it.
However, when you provide more than one argument to the constructor, such as when you do Array(1, 2, 3, 4), the constructor will use the arguments object to instantiate and populate an Array object correctly.
For this reason, we can use Array.apply(null, Array(x)), because the apply function will spread the arguments into the constructor. For clarification, doing Array.apply(null, Array(3)) is equivalent to doing Array(null, null, null).
Now that we've created an actual populated array, all we need to do is call map and create the second layer (y).
One liner to create a m*n 2 dimensional array filled with 0.
new Array(m).fill(new Array(n).fill(0));
Just started using javascript and I need a 2D-Array (coming from C++ where this is pretty normal) but I am not sure how to declare such an array and initialise it with zeros.
Thank you
Edit: After searching a bit I came across this(if anyone could explain me how it does it I would really appreciate it - I can use it but its better to fully understand it)
let Table = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));
const rows = 4;
const cols = 5;
const visited1 = new Array(rows); // create an empty array of length n
for (let i = 0; i < rows; i++) {
visited1[i] = new Array(cols); // make each element an array
}
for(let i = 0;i<rows;i++){
for(let j = 0;j<cols;j++)
visited1[i][j]=false;
}
const visited2 = new Array(rows).fill((new Array(cols)).fill(false))
console.log('visited1 is \n',visited1)
console.log('visited2 is \n',visited2)
visited1[1][1]=true;
visited2[1][1]=true;
console.log('after changes, visited 1 is \n',visited1)
console.log('after changes, visited 2 is \n',visited2)
Why are the 2 arrays visited1 and visited2 behaving differently when i alter the value at an index?
Spent around an hour debugging a code where I was trying to implement a breadth first search. I created a visited matrix to keep track of all vertices I have already visited using the Array.fill() method , but when i modify visited[i][j], it changes the entire column instead of just the value at that index. Why is this happening?
I'm making a wordle copy in react, and wanted to initialize all the boxes in one go, after an hour or 2 of debugging and wondering why when I entered a letter, all the boxes would fill up with the letter, I realized it was because a made an array of references to the same object.
So after another hour I came to this solution:
Array(6).fill(null).map(() =>Array(5).fill(null).map(() => ({ ...box })))
Another view:
Array(6).fill(null).map(() =>Array(5).fill(null).map(() => ({ ...box })))
I was wondering how god awful this is. And what a better solution would be.
Should I scrap the array of objects and just have an array of letters? This was v1 of the project but, playing with the position and indexes of the letters and words was a nightmare.
You are reinitializing the empty array in every loop iteration:
array1[i]=[];
When you should only be doing this once per value of i. Move the initialization out of the inner-most loop.
Here is how it should be
n=2; //rows
m=3; //columns
z=0;
array1=[];
for(i=0;i<n;i++){
array1[i]=[];
for(j=0;j<m;j++){
array1[i].push(z); // Here is my change
console.log(i+","+j+"="+z); //debug
z++;
}
}