How to Create a Two-Dimensional Array in JavaScript?

  • By Mayuresh Marale
  • November 11, 2023
  • JavaScript
How to Create a Two-Dimensional Array in JavaScript?

How to Create a Two-Dimensional Array in JavaScript?

A two-dimensional array, also known as a 2D array, is a collection of data elements arranged in a grid-like structure with rows and columns. Each element in the array is referred to as a cell and can be accessed by its row and column indices/indexes. In this BLog, we will discover more about How to Create a Two-Dimensional Array in JavaScript?

[ a1, a2, a3, …, an,

  b1, b2, b3, …, bn,

  c1, c2, c3, …, cn,

  .

  .

  z1, z2, z3, …, zn ]

 

In JavaScript, there is no direct syntax for creating 2D arrays as with other commonly used programming languages like C, C++, and Java.

 

For Free Demo classes Call: 020-71173125

Registration Link: Click Here!

 

You can create two-dimensional arrays in JavaScript through jagged arrays — an array of arrays. For example, below is what a jagged array looks like:

let two_dimensional_array = [ 

[ a1, a2, a3, …, an ],

[ b1, b2, b3, …, bn ],

[ c1, c2, c3, …, cn ],

.

.

[ z1, z2, z3, …, zn ] 

];

 

How to Access Elements in a JavaScript 2D Array?

You can access the elements of a two-dimensional array using two indices, one for the row and one for the column. Suppose you have the following two-dimensional array:

let Marks = [

    [‘Yudhisthir’, 90, ‘O’],

    [‘Bhim’, 80, ‘A’],

    [‘Arjun’, 70, ‘A’],

    [‘Nakul’, 60, ‘B’],

    [‘Sahdev’, 50, ‘B’]

];

 

The above is a jagged array in which each element holds the name, marks, and grade. You can access specific elements using the row and column index as seen in the syntax below:

arrayName[rowIndex][columnIndex]

 

For Free Demo classes Call: 020-71173125

Registration Link: Click Here!

 

How to Access the First and Last Elements of a 2D array?

Sometimes you might need to find the first and last elements of a two-dimensional array. You can do this using the first and last index of both the rows and columns.

The first element will always have the row and column index of 0, meaning you will use arrayName[0][0].  Join Our Expert-Led React JS Training in Pune for Dynamic Web Development. Hands-On Learning for Future-Ready Web Apps. Enroll Now!

The index of the last element can be tricky, however, as follows:

 

// returns first element “Yudhisthir”

console.log(marks[0][0]);

// returns last element “B”

console.log(marks[marks.length-1][marks[marks.length-1].length – 1]); 

 

How to Add all Elements of a 2D Array?

In some situations, all the elements of your 2D array can be numbers, so you may need to add them together and arrive at just one digit. You can do this using a nested loop. You will first loop through the rows, then, for each row, you loop through its elements.

let numbers = [

    [10, 20, 60],

    [8, 10, 52],

    [15, 5, 24]

];

var sum = 0;

numbers.forEach((row) => {

    row.forEach((element) => {

        sum += element;

    });

});

// returns “sum : 204”

console.log(“sum : ” + sum); 

 

How to Insert an Element into a 2D Array?

You can add an element or many elements to a 2D array with the push() and unshift() methods.

 

For Free Demo classes Call: 020-71173125

Registration Link: Click Here!

 

The push() method adds elements(s) to the end of the 2D array, while the unshift() method adds element(s) to the beginning of the 2D array.

marks.unshift([“Karna”, 99, “O”]);

marks.push([“Duryodhan”, 10, “F”]);

 

When you console.log(), you will see that the new rows have been added:

[

    [“Karna”, 9, “O”],

    [‘Yudhisthir’, 90, ‘O’],

    [‘Bhim’, 80, ‘A’],

    [‘Arjun’, 70, ‘A’],

    [‘Nakul’, 60, ‘B’],

    [‘Sahdev’, 50, ‘B’],

    [“Duryodhan”, 10, “F”]

]

 

How to Remove an Element From a 2D Array?

You can also remove element(s) from the beginning and end of a 2D array with the pop() and shift() methods. This is similar to how the push() and unshift() methods work, but you do not add any parameters to the methods this time.

marks.pop()

marks.shift()

 

When you console.log() the array, you will see that the first and last array elements have been removed:

[

    [‘Yudhisthir’, 90, ‘O’],

    [‘Bhim’, 80, ‘A’],

    [‘Arjun’, 70, ‘A’],

    [‘Nakul’, 60, ‘B’],

    [‘Sahdev’, 50, ‘B’]

]

 

You can also remove elements from each array element:

marks.forEach((each) => {

  each.pop();

});

This will return:

[

    [‘Yudhisthir’, ‘O’],

    [‘Bhim’, ‘A’],

    [‘Arjun’, ‘A’],

    [‘Nakul’, ‘B’],

    [‘Sahdev’, ‘B’]

]

 

You can also use the splice() method to remove array elements from specific positions:

 

arrayName.splice(start_index, delete_count, insert_items)

 

Applying splice method as follows:

marks.forEach((each) => {

  each.splice(1,1);

});

 

This will return:

[

    [‘Yudhisthir’],

    [‘Bhim’],

    [‘Arjun’],

    [‘Nakul’],

    [‘Sahdev’]

]

Do watch our Components Of Angular video on YouTube.

 

Author:-

Mayuresh Marale

Call the Trainer and Book your free demo Class For Javascript

Call now!!! | SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*