Open In App

JavaScript 2D Arrays

Last Updated : 22 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Generally, in JavaScript, we deal with one-dimensional or linear arrays that contain multiple elements of the same type stored at different memory locations with the same name. But, there are also 2D array concepts that exist in JavaScript.

What are 2D Arrays?

A 2D array is commonly known as an array of arrays in JavaScript. It is an array that consists of multiple arrays stored at different memory locations but with the same name. The 2D arrays are just like the matrices in mathematics. Every cell of the array can be considered as a row and the array contained by that particular cell can be considered as columns.

Example:

[
[1, 2, 3],
[col1, col2, col3],
[ele1, ele2, ele3]
]

NOTE: JavaScript does not provide any direct syntax to create 2D arrays. However, you can use the jagged array syntax or the array of arrays syntax to create 2D arrays in JavaScript.

What is the use of 2D arrays?

The 2D arrays can be used to store and manipulate the data in a structured or organized manner. Below listed some of general use cases of the 2D arrays in JavaScript.

  • It helps to efficiently store and manipulate the large amount of the data like images, videos or other files.
  • They can be used to implement the matrix operations like transpose, multiplication etc.
  • These arrays generally used in the application where the data needs to be store in a table or requires image processing.
  • They can be used to represent the wide range of data like graphs, maps, tables, matrices etc.

Example 1: The below code example shows how you can define a 2D array in JavaScript.

Javascript




const arrOfArr =
[
    [1, 2, 3],
    ["str1", "str2"],
    [true, false]
];
 
console.log("2D Arrays in JS: ", arrOfArr);


Output

2D Arrays in JS:  [ [ 1, 2, 3 ], [ 'str1', 'str2' ], [ true, false ] ]

Example 2: The below code explains how you can access the 2D array elements in JavaScript.

Javascript




const arrOfArr =
[
    [1, 2, 3],
    ["str1", "str2"],
    [true, false]
];
 
console.log("First array last element: ", arrOfArr[0][2]);
console.log("Second array second element: ", arrOfArr[1][1]);
console.log("Third array first element: ", arrOfArr[2][0]);


Output

First array last element:  3
Second array second element:  str2
Third array first element:  true

Limitations of 2D arrays

  • The size of the 2D arrays is fixed, once it is created it can not be modified.
  • The array methods like map(), filter(), and reduce() may not be as convenient with 2D arrays as with linear arrays.
  • It is a bit complex to access the array values when working with large data set.
  • It requires the nested loops to access the elements or to operate any operations on them.
  • Irregularity of the number of elements inside a nested array.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads