Updated April 10, 2023
Introduction to 2D Arrays in JavaScript
Two-dimensional arrays are a collection of homogeneous elements that span over multiple rows and columns, assuming the form of a matrix. Below is an example of a 2D array which has m rows and n columns, thus creating a matrix of mxn configuration. In this topic, we are going to learn about 2D Arrays in JavaScript.
[ a1, a2, a3, a4, ..., an
b1, b2, b3, b4, ..., bn
c1, c2, c3, c4, ..., cn
.
.
.
m1, m2, m3, m4, ..., mn]
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.
A two-dimensional array in JavaScript is a jagged array of multiple one-dimensional arrays. Thus, a jagged array may look something like this:
[ [ a1, a2, a3, a4, ..., an ],
[ b1, b2, b3, b4, ..., bn ],
[ c1, c2, c3, c4, ..., cn ],
.
.
.
[ m1, m2, m3, m4, ..., mn ] ]
True 2D Arrays vs Jagged Arrays
Programming languages differ in their implementation of multidimensional arrays. Some programming languages like C, C++, C#, Fortran, etc. support true 2D arrays. While there are others that simulate this behavior with arrays of arrays a.k.a. jagged arrays. So, how is a true two-dimensional array different from jagged arrays?
The two implementations of multidimensional arrays are different in terms of storage consumption. While a true 2D array would have m rows of n elements each, a jagged array could have m rows each having the different numbers of elements. This leads to a minimum wasted space for sets of data. Thus, the below-jagged array is perfectly fine:
int[][] jaggedArray = [ [1, 2, 3, 4],
[5, 6, 7],
[8, 9] ]
If the same data set were to be implemented in a true 2D array, it would have been as below:
int[,] multiDimArray = [ 1, 2, 3, 4
5, 6, 7, 0
8, 9, 0, 0 ]
How to Create 2D Arrays in JavaScript?
Note – Throughout the examples in this article, we would be using the developer console of the browsers. Simply open the browser developer tools (Ctrl/Cmd + Shift + C) and go to the Console tab in the developer tools window.
It looks like this in Chrome:
This is the playground for most of the JavaScript related concepts. We would be using this playground throughout this article.
Using square brackets
If you have a finite and small number of elements, you can simply create a 2D array in JavaScript with the below syntax:
var varName = [
[ elements ],
[ elements ],
[ elements ] ... ];
Example
The below example creates a chessboard with 2D Array implementation.
var chessBoard = [
['R','N','B','Q','K','B','N','R'],
['P','P','P','P','P','P','P','P'],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
['p','p','p','p','p','p','p','p'],
['r','n','b','q','k','b','n','r'] ];
console.log(board.join('\n'));
Output
Using new()constructor
When you do not know the elements beforehand, you can simply create an array using for loop and a new constructor. JavaScript will initialize each element with the undefined value.
Example
var array2D = new Array(8);
for(var i = 0; i< array2D.length; i++){
array2D[i] = new Array(8);
};
console.log(array2D);
Output
This creates an empty array of 8 empty arrays.
Avoid the new() operator.
Note – It is recommended to use the square bracket method of creating arrays in JavaScript. This is because using the new method tells the interpreter to invoke the Array constructor. This is extra work for the interpreter, as it has to search globally for the Array constructor and then invoke it.
Moreover, if you overwrite the Array constructor with your own custom definition, the interpreter would invoke your custom constructor and not the global Array constructor. This can lead to confusion and inconsistency throughout the application.
Operations on 2D Arrays in JavaScript
Now that we have created our 2D array in JavaScript, let us learn what operations can be performed on this array. We would look at how to access, insert, remove and update elements in our array.
So, we create an array and initialize it with values as below:
var array2D = new Array(8);
for(var i = 0; i< array2D.length; i++){
array2D[i] = new Array(i, i+1, i+2, i+3, i+4, i+5, i+6,
i+7);
};
console.log(array2D);
Output:
Access elements
To access elements in our array, we use square bracket notations. Note that JavaScript only supports integer-based indexes in arrays. String-based indexes change the type of our variable from an Array to an Object and cause it to lose some of its properties as an Array.
array2D[2][4] // this is right
array2D['abc']['xyz'] //this is no longer an Array
So, to access the elements of our array, we would use integer-based indexes.
Access First and Last Element
// This gives us the first element
console.log("First Element : " + array2D[0][0]);
// This gives us the last element
console.log("Last Element : " + array2D[array2D.length -
1][(array2D[array2D.length -1]).length - 1]);
Output:
Accessing the last element was pretty straightforward. We know that the index of the first element would be [0, 0]. But, we don’t know the index of the last element. So, to access the last element, we used the length property of the Array.
Since the index starts at 0, the last index would always be one less than the length of the array. So, we determined the length of the outer array and the length of the last jagged array to get both the x and y indices.
Looping through all the elements
We can loop through all the elements in the array using either for loop or forEach loop. We have already seen for a loop when we created and initialized our array. Let us now try to get the sum of all the elements in our array using a forEach loop.
var sum = 0;
array2D.forEach((x) => {
x.forEach((y) => {
sum += y;
})
})
console.log("The sum of all elements in the array is :" +sum);
Output:
Insert/Remove Elements – push & pop
Inserting at the end of Array
We can insert new elements in our array using the push() method. The push() method inserts elements at the end of the array.
var newLength = array2D[array2D.length - 1].push(111);
console.log("Element added : " + array2D[array2D.length - 1]
[newLength - 1]);
Output:
The push() method returns the updated length of the array. We can capture the new length in a variable and use it further in our application.
Removing from the end of Array
We can remove the elements in our array using the pop() method. This method removes the last element from the array.
var ele = array2D[array2D.length - 1].pop();
console.log("Element removed : " + ele);
Output:
The pop() method returns the element that was removed from the array.
Insert/Remove Elements – splice
The splice() method is used to modify the array contents by adding, removing, or replacing the elements in the array.
The syntax of the splice() method is:
array.splice(start, deleteCount, ...items)
Inserting at a given index
We can insert new elements in our array using the splice() method. To do so, we specify the deleteCount property as 0 in the splice method. The items that we mention as arguments are then inserted in the array at the index specified by the start parameter.
array2D[2].splice(3, 0, 4.2, 4.5, 4.8);
console.log(array2D[2]);
Output:
Removing from a given index
In a similar way, we can use the splice() method to remove the elements from the given index. To do so, we specify the index in the start parameter followed by the number of elements to be deleted in the deleteCount parameter. If deleteCount is not specified, all the elements from the start till the end of the array are deleted.
array2D[2].splice(3, 3);
console.log(array2D[2]);
Output:
Update Elements
Just like accessing elements in an array, we can also update the elements. All we need to know is the right indices of the elements to be updated.
The code below updates all the elements of our array and squares them.
for(var i = 0; i < array2D.length; i++){
for(var j = 0; j < array2D[i].length; j++){
array2D[i][j] *= array2D[i][j];
}
}
console.log(array2D);
Output:
Conclusion
We have seen that arrays in JavaScript are jagged arrays. This may be a little tough to understand and get used to in the beginning, but once you understand the concept of jagged arrays, working with JavaScript arrays can become easy.
We have covered the basics of JavaScript arrays – creation, insertion, removal and updating elements. There are a lot of other methods in JavaScript arrays that are very beneficial for the development of good and robust JavaScript applications. It is recommended to dive a little deeper into arrays and explore other methods that make working with arrays even more convenient.
Recommended Articles
This is a guide to 2D Arrays in JavaScript. Here we discuss How to Create 2D Arrays in JavaScript along with the operation and the Concept of Jagged Arrays. You may also have a look at the following articles to learn more –