Last modified: Jul 31, 2026
JavaScript Array of Arrays Guide
Arrays are powerful in JavaScript. But sometimes you need more than a simple list. You need a grid, a table, or a matrix. That's where an array of arrays comes in. This guide will teach you everything about nested arrays. You'll learn to create them, access them, and change them.
Think of an array of arrays as a spreadsheet. The outer array is like the rows. Each inner array is a single row with its own cells. This structure is also called a multidimensional array. It's a fundamental concept for many coding tasks. Let's dive in and make it simple.
What Is an Array of Arrays?
An array of arrays is simply an array where each element is another array. It's a way to store data in a table-like format. You can have rows and columns. You can also have more complex structures, like arrays within arrays within arrays. But we'll start with the basics.
This structure is useful for representing grids, matrices, or any data that has a natural row-and-column layout. For example, you might store game boards, pixel data, or a list of student grades. The outer array holds all the rows. Each inner array holds the values for that specific row.
How to Create an Array of Arrays
Creating a nested array is straightforward. You just put arrays inside an array literal. Use square brackets for the outer array. Inside, you put other square brackets for each inner array. Here’s a simple example:
// Create a 2x3 array (2 rows, 3 columns)
const matrix = [
[1, 2, 3],
[4, 5, 6]
];
console.log(matrix);
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
You can also create an empty array and then push inner arrays into it. This is useful when you don't know the data upfront. Let's see how that works.
// Create an empty outer array
const grid = [];
// Add rows using push()
grid.push([10, 20]);
grid.push([30, 40]);
console.log(grid);
console.log(grid.length); // 2 (outer array length)
[ [ 10, 20 ], [ 30, 40 ] ]
2
Notice that the length property of the outer array gives you the number of rows. It doesn't care how many items are in each inner array. This is a key point to remember.
Accessing Elements in Nested Arrays
To get a value from a nested array, you use two sets of square brackets. The first bracket picks the row (the inner array). The second bracket picks the element within that row. Here's the pattern: outerArray[rowIndex][columnIndex].
Remember, indices start at 0. So the first row is index 0, and the first column is index 0. Let's look at a practical example.
const matrix = [
[1, 2, 3],
[4, 5, 6]
];
// Access the element in the first row, second column (value 2)
const value = matrix[0][1];
console.log(value); // 2
// Access the element in the second row, third column (value 6)
console.log(matrix[1][2]); // 6
// Access the entire second row
console.log(matrix[1]); // [4, 5, 6]
2
6
[ 4, 5, 6 ]
You can also use this method to modify elements. Just assign a new value to the specific index. It's as easy as accessing them.
const gameBoard = [
['X', 'O', 'X'],
['O', 'X', 'O']
];
// Change the top-right corner from 'X' to 'O'
gameBoard[0][2] = 'O';
console.log(gameBoard);
[ [ 'X', 'O', 'O' ], [ 'O', 'X', 'O' ] ]
This direct access is powerful. It allows you to read and write data at any specific point in your grid. This is essential for many algorithms and data manipulations.
Iterating Over an Array of Arrays
Often, you'll need to go through every element in your nested array. The best way is to use nested loops. The outer loop goes through the rows. The inner loop goes through the columns in each row. Here's a classic example.
const matrix = [
[1, 2, 3],
[4, 5, 6]
];
// Loop through each row
for (let i = 0; i < matrix.length; i++) {
// Loop through each column in the current row
for (let j = 0; j < matrix[i].length; j++) {
console.log(`Element at [${i}][${j}] is ${matrix[i][j]}`);
}
}
Element at [0][0] is 1
Element at [0][1] is 2
Element at [0][2] is 3
Element at [1][0] is 4
Element at [1][1] is 5
Element at [1][2] is 6
You can also use the forEach() method. It's cleaner for some developers. You just nest one forEach() inside another. The inner function gets the element and its index. The outer function gets the inner array.
const matrix = [
[10, 20],
[30, 40]
];
matrix.forEach((row, rowIndex) => {
row.forEach((value, colIndex) => {
console.log(`Row ${rowIndex}, Col ${colIndex}: ${value}`);
});
});
Row 0, Col 0: 10
Row 0, Col 1: 20
Row 1, Col 0: 30
Row 1, Col 1: 40
For more advanced data transformations, you might want to use the map() method. It creates a new array based on the original. This is great for changing all values in a grid. If you need to sum all elements, check out our guide on JavaScript Array reduce() Explained.
Common Operations and Methods
Many standard array methods work on the outer array. But you need to remember they operate on the inner arrays as a whole. For example, push() adds a new row. pop() removes the last row. Let's see these in action.
const matrix = [[1, 2], [3, 4]];
// Add a new row
matrix.push([5, 6]);
console.log(matrix); // [[1,2], [3,4], [5,6]]
// Remove the last row
matrix.pop();
console.log(matrix); // [[1,2], [3,4]]
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
[ [ 1, 2 ], [ 3, 4 ] ]
You can also use methods like splice() to add or remove rows at specific positions. It works exactly like it does on a flat array, but the elements are arrays. This gives you a lot of control over your data structure.
To flatten a nested array into a single array, you can use the flat() method. This is very handy when you need to process all values without worrying about the structure. It creates a new array with all sub-array elements concatenated into it.
const nested = [[1, 2], [3, [4, 5]]];
const flat = nested.flat(2); // Depth of 2
console.log(flat); // [1, 2, 3, 4, 5]
[ 1, 2, 3, 4, 5 ]
This is a great way to simplify your data. If you need to convert the entire grid into a string, you might find our article on JavaScript Array to String useful.
Practical Examples and Use Cases
Let's look at a real-world example. Suppose you're tracking student scores. You have several students, and each has three test scores. This is a perfect case for an array of arrays.
const studentScores = [
[85, 90, 78], // Student 1
[92, 88, 95], // Student 2
[70, 75, 80] // Student 3
];
// Calculate average for each student
for (let i = 0; i < studentScores.length; i++) {
const scores = studentScores[i];
let sum = 0;
for (let j = 0; j < scores.length; j++) {
sum += scores[j];
}
const average = sum / scores.length;
console.log(`Student ${i + 1} average: ${average.toFixed(2)}`);
}
Student 1 average: 84.33
Student 2 average: 91.67
Student 3 average: 75.00
Another common use is for a tic-tac-toe board. You can easily check for a win condition by accessing specific cells. The grid structure makes it very intuitive to model the game state.
You might also want to convert a 2D array into an array of objects. This is a common data transformation task. For that, you can use the map() method combined with object creation. If you need a refresher on objects, see our JavaScript Array of Objects Guide. For destructuring, check out JavaScript Array Destructuring Guide.
Common Pitfalls and Tips
One common mistake is assuming all inner arrays have the same length. JavaScript doesn't enforce this. You can have rows of different sizes. Always check the length of each inner array before accessing its elements to avoid errors.
Another pitfall is shallow copying. If you use slice() or the spread operator on the outer array, you only copy the references to the inner arrays. Modifying an inner array will affect the original. For a deep copy, you need to map and copy each inner array.
const original = [[1, 2], [3, 4]];
// Shallow copy (bad for nested arrays)
const shallowCopy = original.slice();
shallowCopy[0][0] = 99;
console.log(original[0][0]); // 99 (changed!)
// Deep copy (good)
const deepCopy = original.map(row => [...row]);
deepCopy[0][0] = 100;
console.log(original[0][0]); // 99 (unchanged)
99
99
Also, remember that the length of the outer array is the number of rows, not the total number of elements. To get the total, you need to sum the lengths of all inner arrays. This is a common source of confusion.
Conclusion
Arrays of arrays are a versatile tool in JavaScript. They allow you to represent complex, structured data easily. You've learned how to create them, access their elements, and iterate over them. You've also seen how to use common array methods on them.
Remember the key concepts: use double brackets for access, nested loops for iteration, and be careful with copying. With these skills, you can handle grids, matrices, and tables with confidence. Practice with your own examples to solidify your understanding. Happy coding!