JavaScript Array of Arrays
Last Updated :
29 Nov, 2024
An array of arrays also known as a multidimensional array is simply an array that contains other arrays as its element. This structure allows you to store and organize data in a tabular format or a nested structure, making it easier to work with complex data in your applications.
JavaScript
let mat = [
[1, 2, 3], // First sub-array
[4, 5, 6], // Second sub-array
[7, 8, 9] // Third sub-array
];
console.log(mat[0][1]);
- The outer array contains three inner arrays.
- Each inner array has its own set of numbers.
Accessing Elements in an Array of Arrays
To access an element inside an array of arrays, you need to specify two indices:
- The first index refers to the array (or row).
- The second index refers to the element within that array (or column).
JavaScript
let mat = [
[1, 2, 3], // First array
[4, 5, 6], // Second array
[7, 8, 9] // Third array
];
// Accessing the element at the second row, third column
console.log(mat[1][2]);
In this case, mat[1][2] refers to the element in the second sub-array ([4, 5, 6]) at the third position (which is 6).
Modifying Elements in an Array of Arrays
Just like regular arrays, you can modify the elements inside an array of arrays using their indices.
JavaScript
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Changing the element at the first row, second column to 10
mat[0][1] = 10;
console.log(mat);
Output[ [ 1, 10, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Here, we modify the value at index [0][1], changing 2 to 10.
Looping Through an Array of Arrays
You can use loops (like for, forEach, or map) to iterate through an array of arrays and access each individual element.
JavaScript
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Using nested loops to access each element
for (let i = 0; i < mat.length; i++) {
for (let j = 0; j < mat[i].length; j++) {
console.log(mat[i][j]);
}
}
Array of Arrays: Practical Uses
1. Representing a Matrix
An array of arrays is commonly used to represent a matrix (a grid of rows and columns). For example, a 3x3 matrix of numbers could be represented like this:
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
This is ideal for operations such as matrix multiplication or performing transformations in graphics programming.
2. Storing Tables or Grids
In web development, an array of arrays can represent data in a tabular format, where each row is an array containing the columns:
let table = [
["Name", "Age", "City"],
["Amit", 25, "Delhi"],
["Rohit", 30, "Chennai"],
["Pankaj", 35, "Amritsar"]
];
This could be useful when dealing with dynamic tables or grids of data, such as in spreadsheets or dashboards.
3. Storing Grouped Data
An array of arrays is also useful for organizing grouped data, such as storing lists of items in different categories:
let mat = [
["Apple", "Banana", "Cherry"], // Fruits
["Carrot", "Lettuce", "Spinach"], // Vegetables
["Chicken", "Beef", "Pork"] // Meats
];
Here, each sub-array represents a group of related items.
Flattening an Array of Arrays
Sometimes, you might want to convert a nested array into a single array. This is known as flattening the array. JavaScript provides a convenient method flat() to achieve this.
JavaScript
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Flattening the array of arrays
let flatA = mat.flat();
console.log(flatA);
Output[
1, 2, 3, 4, 5,
6, 7, 8, 9
]
The flat() method combines all elements into a single array.
Array of Different Sizes
In JavaScript, arrays can have different sizes, meaning they can hold any number of elements. You can add or remove items from an array, and its size will change accordingly.
JavaScript
// Array of arrays with different sizes
let arrOfArr = [
[1, 2, 3], // Array of size 3
[4, 5], // Array of size 2
[6, 7, 8, 9], // Array of size 4
[10] // Array of size 1
];
// Accessing individual arrays
console.log(arrOfArr[0]);
console.log(arrOfArr[1]);
console.log(arrOfArr[2]);
console.log(arrOfArr[3]);
Output[ 1, 2, 3 ]
[ 4, 5 ]
[ 6, 7, 8, 9 ]
[ 10 ]
Array of different types
This code creates a 2D array where each sub-array contains different types of data, such as strings, numbers, mixed types, and objects. You can access specific elements by referencing their row and column indices.
JavaScript
let mergedArray = [
[ "apple", "banana", "cherry" ], // Array of strings
[ 10, 20, 30, 40 ], // Array of numbers
[42, "hello", true, 3.14], // Array of mixed types (numbers, strings, booleans)
[{name : "Alice", age : 25}, {name : "Bob", age : 30}] // Array of objects
];
// Accessing elements from each sub-array
console.log(mergedArray[0][1]);
console.log(mergedArray[1][2]);
console.log(mergedArray[2][3]);
console.log(mergedArray[3][1].name);
Similar Reads
JavaScript Array Exercise
In JavaScript, an Array is a versatile data structure that allows you to store multiple values in a single variable. Arrays can hold different data types, including strings, numbers, objects, and even other arrays. JavaScript arrays are dynamic, which means they can grow or shrink in size.JavaScript
1 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 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
JavaScript Multidimensional Array
A multidimensional array in JavaScript is an array that contains other arrays as its elements. These are often used to represent data in a grid or matrix format. In JavaScript, there is no direct syntax for multidimensional arrays, but you can achieve this by creating arrays within arrays.Creating a
4 min read
TypeScript Arrays
An array is a user-defined data type. An array is a homogeneous collection of similar types of elements that have a contiguous memory location and which can store multiple values of different data types.An array is a type of data structure that stores the elements of a similar data type and consider
5 min read
How to Convert an Array into a Complex Array JavaScript ?
Complex arrays can represent multiple dimensions or data with a structure. This article discusses two approaches to converting an array into a more complex array.Table of ContentUsing Multidimensional ArraysUsing Array.from()Using the reduce() MethodUsing the map() Method with slice() MethodUsing Mu
3 min read
JavaScript Array Interview Questions and Answers
JavaScript Array Interview Questions and Answers contains the list of top 50 array based questions that are frequently asked in interviews. The questions list are divided based on difficulty levels (Basic, Intermediate, and Advanced). This guide covers fundamental concepts, common problems, and prac
15+ min read
JavaScript Arrays Coding Practice Problems
Arrays are one of the most fundamental data structures in JavaScript, allowing efficient storage and manipulation of data. This curated list of Coding Practice Problems will help you to master JavaScrip Arrays. Whether you're a beginner or an experienced developer, these problems will enhance your J
2 min read
JavaScript Indexed Collections
Indexed collections in JavaScript refer to data structures like arrays, where elements are stored and accessed by numerical indices. Arrays allow for efficient storage and retrieval of ordered data, providing methods for manipulation and traversal of their elements. Example an array called 'student'
5 min read
JavaScript Program to Construct an Array from its pair-sum Array
The pair-sum array is a unique construction that holds the sum of all potential pairs of elements from the original array. At first glance, it might appear to be challenging, but in this article, we'll Construct an array from its pair-sum array and discover some of its most intriguing uses. What is
4 min read