- Declare an empty two-dimensional array in Javascript?
- 23 Answers 23
- Создайте двумерный массив в JavaScript
- 1. Использование конструктора массива
- 2. Использование литеральной записи массива
- 3. Использование Array.from() функция
- 4. Использование Array.prototype.map() функция
- Dynamically create a two dimensional Javascript Array
Declare an empty two-dimensional array in Javascript?
I want to create a two dimensional array in Javascript where I’m going to store coordinates (x,y). I don’t know yet how many pairs of coordinates I will have because they will be dynamically generated by user input. Example of pre-defined 2d array:
I guess I can use the PUSH method to add a new record at the end of the array. How do I declare an empty two dimensional array so that when I use my first Arr.push() it will be added to the index 0, and every next record written by push will take the next index? This is probably very easy to do, I’m just a newbie with JS, and I would appreciate if someone could write a short working code snippet that I could examine. Thanks
Have you tried var Arr = new Array(new Array()); ? And yes, push and pop add or remove elements from the end of the array, while shift and unshift remove or add elements to the beginning of the array.
This sounds like two different questions. First you want the arbitrary sized array. Then you’re sortof asking a different question that involves the push method. (Also, if you want to answer your own question, I think it’s best to do that in the answer section.) This is a top ranked question in Google for creating a multi-dimensional array in JavaScript, and I know Google doesn’t dictate content here, but I’d say it’s a fundamentally important question with a wide range of wacky answers.
23 Answers 23
You can just declare a regular array like so:
Then when you have a pair of values to add to the array, all you need to do is:
And yes, the first time you call arry.push , the pair of values will be placed at index 0.
> var arry = []; undefined > arry.push([1,2]); 1 > arry [ [ 1, 2 ] ] > arry.push([2,3]); 2 > arry [ [ 1, 2 ], [ 2, 3 ] ]
Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:
> arry.push(100); 3 > arry [ [ 1, 2 ], [ 2, 3 ], 100 ]
this seems like an elegant solution, so I got X and Y coordinates, and I insert them like so: arry.push([x,y]); — but how do I get back later, for example the x coordinate on index 0?
If you want to initialize along with the creation, you can use fill and map.
const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));
5 is the number of rows and 4 is the number of columns.
This works well in declarative contexts too, e.g. pre-allocation of a 2d array as an object member. Perhaps not something that one would design from scratch, but useful for tasks like porting from other languages.
Please also note that here map(() => <>) is used to create a standalone row and it’s necessary. The way of new Array(5).fill(new Array(4).fill(0)) is a very dangerous move. Since all the rows are filled with references to ONE array, if you update arr[0][0] the value of arr[1][0] will be changed too. This may raise very serious and dark issues when you use this array as a cache table.
@Kaihua I am new to JavaScript but used the print format code supplied by Kamil Kiełczewski below and there is no problem with Abhinav’s solution. If any element is modified, there are no changes to any other elements. I suppose that your comment is an analog of shallow copies in Python, but that is not the case here.
@RamazanChasygov The code may look counterintuitive at first glance, but it does behave exactly like it should. When you call Array(5).fill(new Array(4)) , this will happen: new Array(4) will be called exactly once, and this newly created array (with length 4) will then be passed to the fill function. Though there’s only a single object created in memory, and this single object will be used to fill all the array elements, i.e. all the array elements point to the same location in memory.
Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)
let Array2D = (r,c) => [. Array(r)].map(_=>Array(c).fill(0)); let m = Array2D(3,5); m[1][0] = 2; // second row, first column m[2][4] = 8; // last row, last column // print formated array console.log(JSON.stringify(m) .replace(/(\[\[)(.*)(\]\])/g,'[\n [$2]\n]').replace(/],/g,'],\n ') );
Well I copied your code and it threw errors when I tried to access values randomly in the array. However, one tiny modification and it worked: Array
And since you sent me in the right direction and I like your style . upvote . though not sure why you code as-is didn’t quite work for me. Ignoring the typescript casting, the only modfication is ‘fill’ instead of ‘map’
Regarding the fill method, take into account that => «If the first parameter is an object, each slot in the array will reference that object.» Therefore if you do this [. Array(r)].map(x=>Array(c).fill(< x: . y: . >)) you will have the same object per row in your matrix
@AkshayVijayJain because map will not work as we expected on empty array — but answer to this question in details goes beyond the OP question. Ask separate question or find it on SO.
If you want to be able access the matrix like so:
I find it the most convenient to init it in a loop.
var matrix = [], cols = 3; //init the grid matrix for ( var i = 0; i
returns undefined and not the error «Uncaught TypeError: Cannot set property ‘0’ of undefined».
You can nest one array within another using the shorthand syntax:
You can try something like this:-
const arr = new Array(5).fill().map(_ => new Array(5).fill(0)) // ✅
You may ask why did I use map instead of:
const badArr = new Array(5).fill(new Array(5).fill(0)) // ❌
The problem with the example above is that it adds references to the array that was passed into the fill method:
While this one works fine:
An empty array is defined by omitting values, like so:
You can fill an array with arrays using a function:
var arr = []; var rows = 11; var columns = 12; fill2DimensionsArray(arr, rows, columns); function fill2DimensionsArray(arr, rows, columns) < for (var i = 0; i < rows; i++) < arr.push([0]) for (var j = 0; j < columns; j++) < arr[i][j] = 0; >> >
Array(11) 0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let m = 3 // rows let n = 3 // columns let array2D = Array(m).fill().map(entry => Array(n))
This implementation creates a unique subarray for each entry. So setting array2D[0][1] = 'm' does not set each entry's [1] index to 'm'
I know this is an old thread but I'd like to suggest using an array of objects rather than an array of arrays . I think it make the code simpler to understand and update.
// Use meaningful variable names like 'points', // anything better than a bad pirate joke, 'arr'! var points = []; // Create an object literal, then add it to the array var point = ; points.push(point); // Create and add the object to the array in 1 line points.push(); // Create the object from local variables var x = 10; var y = 8; points.push(); // Ask the user for a point too var response = prompt("Please enter a coordinate point. Example: 3,8"); var coords = response.split(",").map(Number); points.push(); // Show the results var canvas = document.getElementById('graph'); var painter = canvas.getContext("2d"); var width = canvas.width, height = canvas.height; var scale = 10, radius = 3.5, deg0 = 0, deg360 = 2 * Math.PI; painter.beginPath(); for (var point of points) < var x = point.x * scale + scale; var y = height - point.y * scale - scale; painter.moveTo(x + radius, y); painter.arc(x, y, radius, deg0, deg360); painter.fillText(`$, $`, x + radius + 1, y + radius + 1); > painter.stroke();
Создайте двумерный массив в JavaScript
В этом посте мы обсудим, как создать двумерный массив в JavaScript.
JavaScript предлагает несколько способов создания двумерного массива фиксированных размеров:
1. Использование конструктора массива
Используя конструктор массива и цикл for, создать двумерный массив в JavaScript очень просто:
2. Использование литеральной записи массива
2D-массивы могут быть созданы с использованием литеральной записи, как показано ниже:
3. Использование Array.from() функция
The Array.from() Метод создает новый экземпляр Array из указанного массива и при необходимости сопоставляет каждый элемент массива с новым значением. Чтобы создать двумерный массив, идея состоит в том, чтобы сопоставить каждый элемент длины M с новым пустым массивом длины N.
4. Использование Array.prototype.map() функция
Кроме того, вы можете напрямую позвонить в map() функцию в массиве, как показано ниже:
Это все о создании двумерного массива в JavaScript.
Средний рейтинг 4.81 /5. Подсчет голосов: 26
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
Dynamically create a two dimensional Javascript Array
This is pretty cut and dry, just set up a nested loop:
var count = 1; var twoDimensionalArray =[]; for (var i=0;i <2;i++) < var data = []; for (var j=0;j<5;j++) < data.push("Test" + count); count++; >twoDimensionalArray.push(data); >
It sounds like you want to map the array of text for each $something element into an outer jagged array. If so then try the following
var outterArray = []; $something.each(function () < var innerArray = []; $(this).somethingElse.each(function () < innerArray.push($(this).text()); >); outterArray.push(innerArray); >); alert(outterArray);
A more flexible approach is to use raw objects, they are used in a similar way than dictionaries. Dynamically expendables and with more options to define the index (as string).
var myArray = <>; myArray[12]="banana"; myArray["superman"]=123; myArray[13]=<>; //here another dimension is created myArray[13][55]="This is the second dimension";
You don't need to keep track of array lengths yourself; the runtime maintains the ".length" property for you. On top of that, there's the .push() method to add an element to the end of an array.
// . innerArray.push($(this).text()); // . outerArray.push(innerArray);
To make a new array, just use [] :
innerArray = []; // new array for this row
Also "outer" has only one "t" 🙂
[SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:var outterArray = []; var outterArray = $('.something').map(function() < // find .somethingElse inside current element return [$(this).find('.somethingElse').map(function() < return $(this).text(); >).get()]; // return an array of texts ['text1', 'text2','text3'] >).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array // notice that this alert text1,text2,text3,text4,text5,text6 alert(outterArray); // even when the array is two dimensional as you can do this: alert(outterArray[0]); alert(outterArray[1]);
test1 test2 test3test4 test5 test6Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/
I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:
// 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array for (var i = 1; i else if ( 2 == i ) < d2Arr[j] = ["left"]; >> tmpRange.setHorizontalAlignments( d2Arr ); >
So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.