Wednesday, November 29, 2023
HomeVideo EditingWorking with 2D Arrays in JavaScript

Working with 2D Arrays in JavaScript


When you already perceive the fundamentals of JavaScript arrays, it is time to take your abilities to the following degree with extra superior subjects. On this sequence of tutorials, you will discover intermediate-level subjects for programming with arrays in JavaScript.

On this tutorial, you will discover ways to work with 2D arrays in JavaScript. JavaScript would not have built-in assist for 2D arrays. This isn’t a giant concern as a result of arrays in JavaScript can include different arrays as their components. Which means that we are able to create 2D arrays in JavaScript by creating an array of arrays.

Let’s evaluate a few of the fundamentals akin to 2D array initialization after which implement extra performance like getting and setting component values in a 2D array.

Creating 2D Arrays in JavaScript

Common arrays in JavaScript are one-dimensional. We create common arrays by both utilizing the literal notation or utilizing the Array constructor as proven under:

1
let numbers = [1, 2, 4, 59, 589, 126];
2
let names = new Array('Peter', 'Adam', 'Andy', 'Jake', 'Andrew');
3

4
console.log(numbers);
5
// Outputs: [ 1, 2, 4, 59, 589, 126 ]
6

7
console.log(names);
8
// Outputs: [ 'Peter', 'Adam', 'Andy', 'Jake', 'Andrew' ]

We are able to create 2D arrays in an analogous method. Right here is an instance:

1
let matrix_a = [[1, 2, 4], [59, 589, 126], [34, 39, 27]];
2
let seating_arrangement = new Array(['Peter', 'Adam', 'Andy'], ['Jake', 'Andrew', 'Sam'], ['Jill', 'Jordan', 'Emma']);
3

4
console.log(matrix_a);
5
// Outputs: [ [ 1, 2, 4 ], [ 59, 589, 126 ], [ 34, 39, 27 ] ]
6

7
console.log(seating_arrangement);
8
/* Outputs:
9
[
10
  [ 'Peter', 'Adam', 'Andy' ],
11
  [ 'Jake', 'Andrew', 'Sam' ],
12
  [ 'Jill', 'Jordan', 'Emma' ]
13
]
14
*/

It is very important keep in mind that not like languages akin to C++, 2D arrays in JavaScript don’t have a set variety of rows and columns. So if we would like our array to be a rectangle—ie. with all of the rows and columns the identical size—we have now to ensure that the subarrays all have the identical size.

In our instance above, we created our matrix_a array with three arrays. This provides three rows to our 2D array. Now every of these arrays had three components of their very own. This resulted in three columns in our 2D array. We might have restricted our third array to solely two components and matrix_a would nonetheless be a 2D array. Nevertheless, it could be a jagged 2D array.

For the remainder of this tutorial, our focus will probably be on working with 2D arrays which have a set variety of rows and columns. Let’s outline an array initialization operate with these constraints in thoughts.

Initializing 2D Arrays in JavaScript

We all know {that a} 2D array consists of an array of arrays which make up its rows and columns. Creating and initializing a 2D array is solely a matter of utilizing the array constructor repeatedly to fill the weather of our fundamental array. The next operate does this for us:

1
operate create_2d_array(rows, columns, worth = 0) {
2
  let array_2d = new Array(rows);
3
  
4
  for(let i = 0; i < rows; i++) {
5
    array_2d[i] = new Array(columns).fill(worth);
6
  }
7
  
8
  return array_2d;
9
}
10

11
matrix_a = create_2d_array(3, 4, 1);
12
console.log(matrix_a);
13
// Outputs: [ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ]
14

15
matrix_b = create_2d_array(4, 3, "Pie");
16
console.log(matrix_b);
17
/* Outputs:
18
[
19
  [ 'Pie', 'Pie', 'Pie' ],
20
  [ 'Pie', 'Pie', 'Pie' ],
21
  [ 'Pie', 'Pie', 'Pie' ],
22
  [ 'Pie', 'Pie', 'Pie' ]
23
]
24
*/

Our operate accepts three arguments, the primary one is the variety of rows which signifies what number of arrays the mum or dad array ought to include. The second argument is the variety of columns which dictates what number of components there ought to be inside every array. Lastly, we have now the third argument which is the worth that we wish to set for every component in our 2D array.

Contained in the operate, we create a for loop that iterates over all of the rows and fills the mum or dad array component with new arrays. We name the fill() methodology on every of those new arrays in an effort to initialize them with our specified worth. All the weather are set to 0 if no worth is offered by the person.

We are able to make our array initialization operate shorter utilizing the built-in map() methodology. Right here is the code for our newer and shorter operate:

1
operate create_2d_array_with_map(rows, columns, worth = 0) {
2
  let array_2d = new Array(rows).fill(0);
3
  return array_2d.map(() => new Array(columns).fill(worth));
4
}

As you may see above, this may give us the identical output as the unique operate. This time, we start as standard with our mum or dad array of row components. Nevertheless, we referred to as the fill() methodology to fill it with zeroes. After that, we referred to as the map() methodology on this array which returned a brand new array with all the weather of the mum or dad array full of arrays of columns variety of components.

A few of you would possibly now be questioning if we are able to make the array initialization operate even shorter by utilizing the fill() methodology twice as an alternative of mapping the values as proven under:

1
operate create_2d_array_wrong(rows, columns, worth) {
2
  return new Array(rows).fill(new Array(columns).fill(worth));
3
}

This may generate an array that appears the identical because the earlier ones, however with a refined drawback. As a result of the new Array(columns) constructor is barely referred to as as soon as, all the column arrays will really be references to the very same array. 

That implies that you will not be capable of replace the person columns independantly.

Getting and Setting Factor Values in 2D Arrays

You most likely already know that we are able to entry an array component at any index by utilizing the index worth and the indexes are zero-based.  Right here is an instance:

1
let names = new Array('Peter', 'Adam', 'Andy', 'Jake', 'Andrew');
2
console.log(names[3]);
3
// Outputs: Jake

We acquired the fourth component in our array by utilizing the index worth 3. Let’s attempt one thing comparable with our 2D arrays.

1
let matrix_a = [[1, 2, 4], [59, 589, 126], [34, 39, 27]];
2
let seating_arrangement = new Array(['Peter', 'Adam', 'Andy'], ['Jake', 'Andrew', 'Sam'], ['Jill', 'Jordan', 'Emma']);
3

4
console.log(matrix_a[1]);
5
// Outputs: [ 59, 589, 126 ]
6

7
console.log(matrix_a[1][1]);
8
// Outputs: 589
9

10
console.log(seating_arrangement[0]);
11
// Outputs: [ 'Peter', 'Adam', 'Andy' ]
12

13
console.log(seating_arrangement[0][2]);
14
// Outputs: Andy
15


As you may see, utilizing a single index worth provides us a component of the mum or dad array and this component is definitely an array itself. Now we have to supply one other index worth to get our component from returned array.

Principally, the primary index worth provides us the array inside which we should always search for the component. We’ll name the primary index worth as row_index. The second index worth provides us the component that we’re in search of inside our array returned array. We’ll name the second index worth as col_index. We are able to use the next assertion to entry any component we would like inside our 2D array.

1
my_2d_array[row_idx][col_idx]

This may turn out to be extra clear from the next code snippet:

1
let seating_arrangement = new Array(['Peter', 'Adam', 'Andy'], ['Jake', 'Andrew', 'Sam'], ['Jill', 'Jordan', 'Emma']);
2

3
console.desk(seating_arrangement);
4
/* Outputs:
5
┌─────────┬─────────┬──────────┬────────┐
6
│ (index) │    0    │    1     │   2    │
7
├─────────┼─────────┼──────────┼────────┤
8
│    0    │ 'Peter' │  'Adam'  │ 'Andy' │
9
│    1    │ 'Jake'  │ 'Andrew' │ 'Sam'  │
10
│    2    │ 'Jill'  │ 'Jordan' │ 'Emma' │
11
└─────────┴─────────┴──────────┴────────┘
12
*/
13

14
console.log(seating_arrangement[0][2]);
15
// Outputs: Andy
16

17

18
console.log(seating_arrangement[2][0]);
19
// Outputs: Jill

Utilizing console.desk() to log our 2D arrays makes them simpler to know.

Within the first case, we acquired the component from the primary row (index 0) and the third column (index 2). This gave us the worth Andy. Equally, we acquired Jill by wanting on the third row and first column.

Now that you understand how to entry component values at a selected row or index, it’s straightforward to set a price for that component utilizing easy project. Right here is an instance:

1
let seating_arrangement = new Array(['Peter', 'Adam', 'Andy'], ['Jake', 'Andrew', 'Sam'], ['Jill', 'Jordan', 'Emma']);
2

3
console.desk(seating_arrangement);
4
/* Outputs:
5
┌─────────┬─────────┬──────────┬────────┐
6
│ (index) │    0    │    1     │   2    │
7
├─────────┼─────────┼──────────┼────────┤
8
│    0    │ 'Peter' │  'Adam'  │ 'Andy' │
9
│    1    │ 'Jake'  │ 'Andrew' │ 'Sam'  │
10
│    2    │ 'Jill'  │ 'Jordan' │ 'Emma' │
11
└─────────┴─────────┴──────────┴────────┘
12
*/
13

14
seating_arrangement[0][2] = 'Olivia';
15

16
seating_arrangement[2][0] = 'Ava';
17

18
console.desk(seating_arrangement);
19
/* Outputs:
20
┌─────────┬─────────┬──────────┬──────────┐
21
│ (index) │    0    │    1     │    2     │
22
├─────────┼─────────┼──────────┼──────────┤
23
│    0    │ 'Peter' │  'Adam'  │ 'Olivia' │
24
│    1    │ 'Jake'  │ 'Andrew' │  'Sam'   │
25
│    2    │  'Ava'  │ 'Jordan' │  'Emma'  │
26
└─────────┴─────────┴──────────┴──────────┘
27
*/

Do you bear in mind once I talked about earlier that creating 2D arrays with two successive calls to the fill() methodology will create points because of all components referring to the identical object? You possibly can confirm this your self with the next code snippet:

1
operate create_2d_array_wrong(rows, columns, worth) {
2
  return new Array(rows).fill(new Array(columns).fill(worth));
3
}
4

5
matrix_a = create_2d_array_wrong(3, 4, 1);
6
console.log(matrix_a);
7
// Outputs: [ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ]
8

9
matrix_a[0][1] = 4;
10

11
console.log(matrix_a);
12
// Outputs: [ [ 1, 4, 1, 1 ], [ 1, 4, 1, 1 ], [ 1, 4, 1, 1 ] ]

We solely modified to worth of component within the first row and second column. Nevertheless, the worth within the second column was up to date for all of the rows.

Setting Complete Row or Column Values

We’ll now discover ways to change the worth of complete row or column in a 2D array.

Changing row values is straightforward as a result of the entire row is principally a person array. The one constraint that we are going to placed on this alternative is that the changing array must have the identical variety of components as our unique array. Right here is our operate that does the alternative:

1
operate replace_row(array_2d, row_array, row_idx) {
2
  let array_2d_columns = array_2d[0].size;
3
  if(row_array.size == array_2d_columns) {
4
    array_2d[row_idx] = row_array;
5
  }
6
}
7

8
let seating_arrangement = new Array(['Peter', 'Adam', 'Andy'], ['Jake', 'Andrew', 'Sam'], ['Jill', 'Jordan', 'Emma']);
9

10
console.desk(seating_arrangement);
11
/* Outputs:
12
┌─────────┬─────────┬──────────┬────────┐
13
│ (index) │    0    │    1     │   2    │
14
├─────────┼─────────┼──────────┼────────┤
15
│    0    │ 'Peter' │  'Adam'  │ 'Andy' │
16
│    1    │ 'Jake'  │ 'Andrew' │ 'Sam'  │
17
│    2    │ 'Jill'  │ 'Jordan' │ 'Emma' │
18
└─────────┴─────────┴──────────┴────────┘
19
*/
20

21
replace_row(seating_arrangement, ['Olivia', 'Ava', 'Sophia'], 1);
22

23
console.desk(seating_arrangement;
24
/* Outputs:
25
┌─────────┬──────────┬──────────┬──────────┐
26
│ (index) │    0     │    1     │    2     │
27
├─────────┼──────────┼──────────┼──────────┤
28
│    0    │ 'Peter'  │  'Adam'  │  'Andy'  │
29
│    1    │ 'Olivia' │  'Ava'   │ 'Sophia' │
30
│    2    │  'Jill'  │ 'Jordan' │  'Emma'  │
31
└─────────┴──────────┴──────────┴──────────┘
32
*/

Changing column values would require us to loop by all of the rows as a result of each component in a column comes from a unique array. We may also embody a situation that checks for a match in variety of rows and the size of the changing column array. Right here is the code for our operate:

1
operate replace_column(array_2d, column_array, col_idx) {
2
  if(column_array.size == array_2d.size) {
3
    for(let i = 0; i < column_array.size; i++) {
4
      array_2d[i][col_idx] = column_array[i];
5
    }
6
  }
7
}
8

9
let seating_arrangement = new Array(['Peter', 'Adam', 'Andy'], ['Jake', 'Andrew', 'Sam'], ['Jill', 'Jordan', 'Emma']);
10
console.desk(seating_arrangement);
11
/* Outputs:
12
┌─────────┬─────────┬──────────┬────────┐
13
│ (index) │    0    │    1     │   2    │
14
├─────────┼─────────┼──────────┼────────┤
15
│    0    │ 'Peter' │  'Adam'  │ 'Andy' │
16
│    1    │ 'Jake'  │ 'Andrew' │ 'Sam'  │
17
│    2    │ 'Jill'  │ 'Jordan' │ 'Emma' │
18
└─────────┴─────────┴──────────┴────────┘
19
*/
20

21
replace_column(seating_arrangement, ['Olivia', 'Ava', 'Sophia'], 1);
22
console.desk(seating_arrangement);
23
/* Outputs:
24
┌─────────┬─────────┬──────────┬────────┐
25
│ (index) │    0    │    1     │   2    │
26
├─────────┼─────────┼──────────┼────────┤
27
│    0    │ 'Peter' │ 'Olivia' │ 'Andy' │
28
│    1    │ 'Jake'  │  'Ava'   │ 'Sam'  │
29
│    2    │ 'Jill'  │ 'Sophia' │ 'Emma' │
30
└─────────┴─────────┴──────────┴────────┘
31
*/

Remaining Ideas

On this tutorial, we have now lined the fundamentals of 2D arrays in JavaScript. Their isn’t any built-in assist for 2D arrays in JavaScript. Nevertheless, we are able to nonetheless create them simply by initializing an array of arrays. This tutorial confirmed us alternative ways of initializing 2D arrays. We additionally discovered the way to get or set the worth of particular person components in our 2D array or change the entire row or column without delay.

It’s also possible to use the built-in array strategies with these 2D arrays to implement extra performance like splicing or slicing the 2D array.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments