Zweidimensionale Arrays in JavaScript (Node.js): Ausführlicher Leitfaden
Two-Dimensional Arrays in JavaScript
What is a Two-Dimensional Array?
Imagine a chessboard or a movie theater with rows and seats. Each seat has two addresses: the row number and the seat number within that row.
In programming, such tables are called two-dimensional arrays (or matrices). They are arrays that contain other arrays inside them.
Two-dimensional arrays help store data that is conveniently represented as a table: class schedules, a treasure island map, game results, or social media post statistics.
How to Create a Two-Dimensional Array
The simplest way is to create an array and list other arrays inside it:
// Creating a 3x4 table
let cinema = [
[1, 2, 3, 4], // first row
[5, 6, 7, 8], // second row
[9, 10, 11, 12] // third row
];
How to Access an Element
To get an element from the table, you need to specify two indices: first the row number, then the column number.
Important: counting starts from zero!
let cinema = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
console.log(cinema[0][0]); // 1 — first row, first seat
console.log(cinema[1][2]); // 7 — second row, third seat
console.log(cinema[2][3]); // 12 — third row, fourth seat
How to Modify an Element
Simply assign a new value using the appropriate indices:
let cinema = [
[1, 2, 3],
[4, 5, 6]
];
cinema[0][2] = 99; // Changing the third element in the first row
console.log(cinema[0]); // [1, 2, 99]
How to Fill an Array from Keyboard Input
Often you need to create an array whose size is specified by the user. Use loops for this:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let rows = 2;
let cols = 3;
let array = [];
// Filling the array manually for example
for (let i = 0; i < rows; i++) {
array[i] = [];
for (let j = 0; j < cols; j++) {
array[i][j] = (i + 1) * 10 + (j + 1); // Just an example of numbers
}
}
console.log(array);
// Output: [ [ 11, 12, 13 ], [ 21, 22, 23 ] ]
How to Iterate Over All Elements (Traversal)
Use nested loops — one for rows, another for columns:
let table = [
[1, 2, 3],
[4, 5, 6]
];
for (let i = 0; i < table.length; i++) {
for (let j = 0; j < table[i].length; j++) {
console.log(`Element [${i}][${j}] = ${table[i][j]}`);
}
}
Analysis of Typical Problems
Problem 1: Creating a Cinema Layout
You need to create a table where each element is a seat number. The user enters the number of rows and seats per row.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter number of rows: ', (rows) => {
rl.question('Enter number of seats per row: ', (cols) => {
rows = Number(rows);
cols = Number(cols);
let layout = [];
for (let i = 0; i < rows; i++) {
layout[i] = [];
for (let j = 0; j < cols; j++) {
layout[i][j] = `R${i+1}S${j+1}`;
}
}
console.log('Hall layout:');
for (let i = 0; i < rows; i++) {
console.log(layout[i].join(' | '));
}
rl.close();
});
});
Problem 2: Finding the Maximum Element
Find the largest number in the table (for example, earthquake magnitude).
let data = [
[4.5, 3.2],
[5.1, 2.8]
];
let maximum = data[0][0];
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].length; j++) {
if (data[i][j] > maximum) {
maximum = data[i][j];
}
}
}
console.log(`Maximum magnitude: ${maximum}`); // 5.1
Problem 3: Replacing Elements Based on a Condition
In a warehouse, you need to replace all items with a quantity of 0 with the value 1 (items have been added).
let warehouse = [
[5, 0, 3],
[0, 8, 2],
[1, 0, 6]
];
for (let i = 0; i < warehouse.length; i++) {
for (let j = 0; j < warehouse[i].length; j++) {
if (warehouse[i][j] === 0) {
warehouse[i][j] = 1;
}
}
}
console.log(warehouse);
// [ [5, 1, 3], [1, 8, 2], [1, 1, 6] ]
Common Beginner Mistakes
- Confusing indices: the first index is the row, the second is the column.
array[row][column] - Forgetting that counting starts from zero: the first element has index 0, not 1.
- Not creating the inner array:
array[i] = []must be written, otherwise an error will occur. - Confusing the length of rows and columns:
array.lengthis the number of rows,array[0].lengthis the number of columns. - Going out of array bounds: if the array is 3x4, then the row indices are 0,1,2 and the column indices are 0,1,2,3.
Final Example: Captain Silver's Island Map
We have a 3x3 map. The symbol 'X' is treasure, 'O' is empty. We need to find the coordinates of the treasure.
let map = [
['O', 'O', 'X'],
['O', 'O', 'O'],
['O', 'O', 'O']
];
let found = false;
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[i].length; j++) {
if (map[i][j] === 'X') {
console.log(`Treasure found! Row ${i+1}, Seat ${j+1}`);
found = true;
}
}
}
if (!found) {
console.log('Treasure not found :(');
}
Why Is This Important?
Two-dimensional arrays are the foundation for working with tables, images (each pixel is an element), games (map, battlefield), databases, and many other things. By learning how to work with them, you will be able to solve real-world programming problems!