How to traverse 2D arrays in JavaScript?
Last Updated :
24 Mar, 2023
A two-dimensional array or simply 2D array is a format to store data in a grid format that is rows and columns format. There is no special way of declaring a 2D array in JavaScript, we can simply pass an array as an element inside another array. the array obtained in this method will be created as a 2D array.
Syntax:
var arr = [[...], [...], ...]
Examples:
Input: grid = [[1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]
Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16
Input: grid = [ [ -1, 2, 3 ], [ 0, 9, 8 ], [ 1, 0, 1 ] ]
Output: -1 2 3 8 1 0 9 0 1
Traversal of 2D Array:
In general, there are two ways of traversing a 2D array. The two methods are:
Approach 1: To solve the problem using BFS traversal follow the below steps:
BFS traversal is also called as level order traversal and we use a queue data structure to implement it. In this algorithm first, all the nodes at the same level are traversed and child nodes are traversed.
Follow the below steps to solve the problem:
- Select the root node and initialize a queue
- Mark the node visited, print it then push it into the queue
- Initialize a 2D array to mark the visited cells and mark the root node as visited
- Now iterate till the queue is not empty and perform the following steps:
- Dequeue the current cell present at the beginning and print it.
- Visit its adjacent cells
- Mark them visited, print it, and enqueue them to queue
Below is the implementation for the above approach:
JavaScript
// Javascript program for the above approach
var ROW = 4;
var COL = 4;
// Direction vectors
var dRow = [-1, 0, 1, 0 ];
var dCol = [0, 1, 0, -1 ];
// Function to check if a cell
// is be visited or not
function isValid(vis, row, col)
{
// If cell lies out of bounds
if (row < 0 || col < 0
|| row >= ROW || col >= COL)
return false;
// If cell is already visited
if (vis[row][col])
return false;
// Otherwise
return true;
}
// Function to perform the BFS traversal
function BFS( grid, vis, row, col)
{
// Stores indices of the matrix cells
var q = [];
// Mark the starting cell as visited
// and push it into the queue
q.push([row, col ]);
vis[row][col] = true;
// Iterate while the queue
// is not empty
while (q.length!=0) {
var cell = q[0];
var x = cell[0];
var y = cell[1];
console.log( grid[x][y] + " ");
q.shift();
// Go to the adjacent cells
for (var i = 0; i < 4; i++) {
var adjx = x + dRow[i];
var adjy = y + dCol[i];
if (isValid(vis, adjx, adjy)) {
q.push([adjx, adjy ]);
vis[adjx][adjy] = true;
}
}
}
}
// Driver Code
// Given input matrix
var grid = [[1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12 ],
[13, 14, 15, 16 ] ];
// Declare the visited array
var vis = Array.from(Array(ROW), ()=> Array(COL).fill(false));
BFS(grid, vis, 0, 0);
Output1
2
5
3
6
9
4
7
10
13
8
11
14
12
15
16
Time Complexity: O(N * M)
Auxiliary Space: O(N * M)
Approach 2: To solve the problem using DFS traversal follow the below idea:
DFS traversal is an algorithm that uses stack data structure to implement LIFO(Last In First Out) principle. In this algorithm, we will first select the node mark it visited and visit all its child nodes. Once no child node is left we will use backtracking to visit the unvisited nodes.
Follow the steps to solve the problem:
- Select the root node and initialize a stack
- Mark the node visited, print it then push it into the stack
- Initialize a 2D array to mark the visited cells and mark the root node as visited.
- Now iterate till the queue is not empty and perform the following steps:
- Pop the element at top of the stack and print it
- Push the adjacent cells into a stack
Below is the implementation for the above approach:
JavaScript
// Javascript program of the above approach
var ROW = 3;
var COL = 3
// Initialize direction vectors
var dRow = [0, 1, 0, -1];
var dCol = [ -1, 0, 1, 0];
// Function to check if mat[row][col]
// is unvisited and lies within the
// boundary of the given matrix
function isValid(vis, row, col)
{
// If cell is out of bounds
if (row < 0 || col < 0
|| row >= ROW || col >= COL)
return false;
// If the cell is already visited
if (vis[row][col])
return false;
// Otherwise, it can be visited
return true;
}
// Function to perform DFS
// Traversal on the matrix grid[]
function DFS(row, col, grid, vis)
{
// Initialize a stack of pairs and
// push the starting cell into it
var st = [];
st.push([ row, col ]);
// Iterate until the
// stack is not empty
while (st.length!=0) {
// Pop the top pair
var curr = st[st.length-1];
st.pop();
var row = curr[0];
var col = curr[1];
// Check if the current popped
// cell is a valid cell or not
if (!isValid(vis, row, col))
continue;
// Mark the current
// cell as visited
vis[row][col] = true;
// Print the element at
// the current top cell
console.log( grid[row][col] + " ");
// Push all the adjacent cells
for (var i = 0; i < 4; i++) {
var adjx = row + dRow[i];
var adjy = col + dCol[i];
st.push([ adjx, adjy ]);
}
}
}
// Driver Code
var grid = [ [ -1, 2, 3 ],
[ 0, 9, 8 ],
[ 1, 0, 1 ] ];
// Stores whether the current
// cell is visited or not
var vis = Array.from(Array(ROW), ()=> Array(COL).fill(false));
// Function call
DFS(0, 0, grid, vis);
Time Complexity: O(N * M)
Auxiliary Space: O(N * M )
Similar Reads
Reverse an Array in JavaScript
Here are the different methods to reverse an array in JavaScript1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array.JavaScriptlet a = [1, 2, 3
3 min read
Types of Arrays in JavaScript
A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
3 min read
How to traverse Doubly Linked List in JavaScript?
This article will demonstrate the Doubly Linked List Traversal using JavaScript. Traversal refers to the steps or movement of the pointer to access any element of the list. Types of Traversal in Doubly Linked List Using JavaScriptNormal Traversal: Traversing the list from Head to Tail of the list.Re
5 min read
How to Paginate an Array in JavaScript?
Pagination is a common requirement in web applications especially when dealing with large datasets. It involves dividing a dataset into smaller manageable chunks or pages. In JavaScript, we can paginate an array by splitting it into smaller arrays each representing a page of the data. Below are the
2 min read
How to Copy Array by Value in JavaScript ?
There are various methods to copy array by value in JavaScript.1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.Syntax
4 min read
How to view array of a structure in JavaScript ?
The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either "double quotes" or 'single quotes'. You can get the structure of by using JSON.stringify() or not, here you will see the
3 min read
How to clone an array in JavaScript ?
In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
How to Loop Through an Array in JavaScript?
Here are the various ways to loop through an array in JavaScript1. Using for LoopThe for loop is one of the most used ways to iterate over an array. It gives you complete control over the loop, including access to the array index, which can be useful when you need to modify elements or perform other
4 min read
How to Filter an Array in JavaScript ?
The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output.Syntaxconst filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note: I
2 min read
How to Declare an Array in JavaScript?
Array in JavaScript are used to store multiple values in a single variable. It can contain any type of data like - numbers, strings, booleans, objects, etc. There are varous ways to declare arrays in JavaScript, but the simplest and common is Array Litral Notations. Using Array Literal NotationThe b
3 min read