Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction  
2.
What is a Two-Dimensional Array?
3.
Why Use a 2D Array in JavaScript?
4.
How to Manipulate 2D Arrays in JavaScript
5.
How to add an element in 2D array
5.1.
javascript
6.
How to remove an element from a 2D array
6.1.
javascript
7.
Methods of creating JavaScript 2d Array
7.1.
Array Constructor in JavaScript
7.2.
javascript
7.3.
Array Literal Notation
7.4.
javascript
7.5.
Array.from() Method
7.6.
javascript
7.7.
Array.prototype.map() Method
7.8.
javascript
7.9.
Access Elements in Javascript 2D Array
8.
Updating Elements 2D Arrays in JavaScript
9.
True 2D Arrays vs Jagged Arrays in JavaScript
10.
Frequently Asked Questions
10.1.
What is a 2D array in JavaScript?
10.2.
How to create a 2D array in JavaScript?
10.3.
What is the length of 2D array in JavaScript?
10.4.
How to fill 2D array in JavaScript?
10.5.
How to pass 2D array in JavaScript?
10.6.
What is the difference between array and 2D array?
11.
Conclusion
Last Updated: Apr 3, 2024
Easy

How to create Two Dimensional Array in JavaScript?

Author Ayush Mishra
1 upvote

Introduction  

The term "multi-dimensional array" can also describe a two-dimensional array. A list of two-dimensional arrays with related data types is kept in the Array. The two-dimensional Array is set up using a matrix, simply a collection of rows and columns.

In this blog, we will discuss creating a javaScript 2d Array. Let's start going!

javascript 2d array

See, Javascript hasOwnProperty

What is a Two-Dimensional Array?

A two-Dimensional Array is a collection of elements arranged in a grid-like pattern, with each value identified by a pair of indices representing its row and column positions. It is commonly used to represent data in a tabular format or solve matrix-related programming problems.

Declaration of 2D array:
To declare a 2D array in JavaScript, you can use array literals with nested arrays to represent rows and columns. For example:

let myArray = [[]];

 

This declares a 2D array named myArray with one row (empty) and one column.
 

Initializing a 2D array:

To initialize a 2D array in JavaScript, you can use nested array literals to define the values for each row and column. For example:

let myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

 

This initializes a 2D array myArray with three rows and three columns, filled with numbers.

Reading a 2D array:

To read values from a 2D array in JavaScript, you can use nested loops to traverse through each row and column, accessing each element individually. For example:

for (let i = 0; i < myArray.length; i++) {
   for (let j = 0; j < myArray[i].length; j++) {
       console.log(myArray[i][j]);
   }
}

 

This code snippet reads each element from the 2D array myArray and logs it to the console.

For example, the following is a jagged array i.e. array where the inner arrays can have different lengths. The first two rows have four elements, while the third row only has two elements.

let jaggedArray =[
  [10, 11, 23, 33],
  [4, 35, 46, 57],
  [8, 19]
]
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why Use a 2D Array in JavaScript?

  • To store and manipulate data in a tabular format, like a spreadsheet or chessboard
     
  • To access and modify individual elements using their row and column index
     
  • To provide a convenient way to iterate over the entire grid
     
  • To solve matrix-related problems or implement graphical user interfaces
     
  • To organize data in a more structured and efficient way

How to Manipulate 2D Arrays in JavaScript

In JavaScript, you can modify 2D arrays using a variety of built-in functions and methods. 

Example:

  1. By using the index, we can directly manipulate the value of the arrays
     
  2. Using push(), pop(), shift(), unshift(), delete(), concat(), sort(), slice(), splice(), reverse() we can change/edit the array
     
  3. Using toString(), we can change the array to string form
     

Learn How to add and remove a new row and element to the 2D array.

How to add an element in 2D array

push() and unShift() are two built-in functions that help to add elements in javascript. We can use for loops also to add data to the elements.

The following example will help you to understand the addition of elements in arrays :

  • javascript

javascript

let score = [
["Jatin", 20, 60, "A"],
["Rahul", 10, 52, "B"],
["Rohit", 5, 24, "F"],
["Kiran", 28, 43, "A"],
["Arvind", 16, 51, "B"]
];
score.push(["Susma", 30, 32, "B"]);
score.unshift(["Jaya", 28, 62, "A"]);
console.log(score);

Output:

add an element

How to remove an element from a 2D array

filter() and splice() are two built-in functions that help to remove elements from a 2D array. If we need to remove specific elements from the array, then use the splice() method and if we need to remove elements from the array based on some condition, then use the filter() method.

The following example will help you to understand the removal of elements in arrays using both filter() and splice() :

  • javascript

javascript

const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
// Remove all elements from the inner arrays that are greater than 5
const newArray = array.map((innerArray) => innerArray.filter((element) => element <= 5));
// If any of the inner arrays are now empty, remove them from the outer array
newArray.splice(newArray.findIndex((innerArray) => innerArray.length === 0), 1);
// Print the original array
console.log("Original array:");
console.log(array);
// Print the newArray variable
console.log("New array:");
console.log(newArray);

Output:

remove element

Methods of creating JavaScript 2d Array

Javascript is scripting as well as a programming language, suggesting some methods of creating Javascript 2d array are:-

  • Array Constructor
     
  • Array Literal Notation
     
  • Array.from() Method
     
  • Array.prototype.map() Method

Array Constructor in JavaScript

Javascript array constructor is used to return the constructor function for the array object. It does not return the function's name, only the reference to the function.

In this part of the " Javascript 2d array," we will create a two-dimensional array using Array Constructor and for a loop.

  • javascript

javascript

const x = 2;
const y= 5;
let a = new Array(x); // create an empty array of length x
for (var i = 0; i < x; i++)
{
 a[i] = new Array(y); // make each element an array
}
console.log(a);

Output

[ [ <5 empty items> ], [ <5 empty items> ] ]

Array Literal Notation

An array literal in Javascript is a list of expressions, each representing an array element and denoted by the symbols'[] '.

In this part of the “ Javascript 2d array,” we will create a two-dimensional array using Array Literal Notation.

  • javascript

javascript

const x = 3;
const  y = 5; // It is not relevant here
let a = [];
for (var i = 0; i < x; i++) {
 a[i] = [];
}
console.log(a);

Output

[ [], [], [] ]

Array.from() Method

The map() method builds a new array from the contents of the calling Array after calling a given function on each element.

When an array is created using an array literal, its elements are initialized with the specified values, and the number of arguments specified determines how long the Array will be.

In this part of the “ Javascript 2d array,” we will create a two-dimensional array using Array.from() Method. Any JavaScript object with the length property or an iterable object will return an array object when called using the Array.from() method.

  • javascript

javascript

const x= 3;
const y= 3;
let a = Array.from(Array(x), () => new Array(y));
console.log(a);

Output

[ [ <3 empty items> ], [ <3 empty items> ], [ <3 empty items> ] ]

Array.prototype.map() Method

In this part of the “ Javascript 2d array,” we will create a two-dimensional array using Array. prototype.map() Method.

  • javascript

javascript

const x = 6;
const y = 4;
let a = Array(6).fill().map(() => Array(y));
console.log(a);

Output 

[ [ <4 empty items> ],
  [ <4 empty items> ],
  [ <4 empty items> ],
  [ <4 empty items> ],
  [ <4 empty items> ],
  [ <4 empty items> ] ]

Access Elements in Javascript 2D Array

In our Array, we use square bracket notations to access the elements. JavaScript only permits arrays with integer-based indexes. String-based indexes convert our variable from an array to an object, losing some of its array-specific characteristics.

The syntax for accessing elements:-

array_2_d[0][3] // right syntax

The syntax for accessing the first and last element:-

// This gives us the first element

console.log("First Element : " + array_2_D[0][0]);

// This gives us the last element

console.log("Last Element : " + array_2_D[array_2_D.length -1][(array_2_D[array_2_D.length -1]).length - 1]);

Updating Elements 2D Arrays in JavaScript

We can update the elements in an array like how we access the elements. The correct indices of the elements that need to be updated are:-

The code that follows squares and updates each element in our Array.

for(var x= 0; x < array_2_D.length; x++)
	{
		for(var y = 0; y< array_2_D[x].length; y++)
			{
				array_2_D[x][y] *= array_2_D[x][y];
			}
	}
console.log(array_2_D);

You can practice by yourself on an online JS editor.

True 2D Arrays vs Jagged Arrays in JavaScript

True 2D Arrays: True 2D arrays in JavaScript have a fixed number of rows and columns, where each row contains the same number of elements. They are created using nested array literals with consistent dimensions. For example:

let true2DArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

 

Jagged Arrays: Jagged arrays in JavaScript are arrays of arrays where the inner arrays can have varying lengths. This creates a "jagged" appearance when visualized as rows and columns. Jagged arrays are created by defining each inner array separately. For example:

let jaggedArray = [[1, 2], [3, 4, 5], [6, 7, 8, 9]];

Frequently Asked Questions

What is a 2D array in JavaScript?

A 2D array in JavaScript is an array of arrays where each element of the main array holds an array of values. It allows for the creation of a grid-like structure, with rows and columns, that can be easily accessed and manipulated using nested loops.

How to create a 2D array in JavaScript?

To create a 2D array in JavaScript, you can declare a variable and assign it an array of arrays, where each inner array represents a row. For Example, array = [[1, 2, 3], [4, 5, 6] be a 2D array of 2 columns and 3 columns.

What is the length of 2D array in JavaScript?

We use .length built-in function to find the length of any array. Let say you have an array:
let arr=[[1,2,3,4],[0,9,8,7],[4,5,6,7]]
and you have to find the length of arr you have to just write :
arr.length, and you will get the length of the array. 

How to fill 2D array in JavaScript?

To fill a 2D array in JavaScript, you can use a nested for loop. Iterate over the outer array and then the inner array, setting each element to the desired value.

How to pass 2D array in JavaScript?

To pass a 2D array in JavaScript, simply include it as an argument when calling a function. JavaScript treats arrays as reference types, so modifications made within the function will reflect outside.

What is the difference between array and 2D array?

An array in JavaScript is a collection of elements stored in a single dimension, while a 2D array consists of arrays within an array, forming rows and columns, adding another dimension.

Conclusion

In this blog, we have studied Javascript 2D Array. JavaScript 2D arrays provide a versatile and powerful way to work with tabular data, matrices, and complex structures. Understanding how to declare, initialize, manipulate, and pass 2D arrays in JavaScript opens up opportunities for building dynamic and interactive web applications with rich data representation and manipulation capabilities.

We sincerely hope that this blog has improved your understanding of Javascript 2d Array, and if you want to learn more, then you can check articles on:-


Check out the following problems - 

Do check out The Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.

Refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Happy learning!

Previous article
Compare Two Arrays in JavaScript
Next article
Javascript Array to JSON
Live masterclass