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 Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS)
DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers
NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers
HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network
A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read