javascript 2d array
In JavaScript, creating a multidimensional array involves nesting arrays within other arrays. Although JavaScript doesn’t directly provide built-in multidimensional arrays, we can simulate them by using arrays inside another array. Let’s explore a couple of ways to define and work with multidimensional arrays:
Array Literals:
let activities = []; // Empty multidimensional array
const matrix = [
[1, 2, 3],
[4, 5, 6]
];
In the matrix array, we have two inner arrays, each containing three elements
Defining Arrays Inside Another Array:
You can manually create a multidimensional array by defining arrays inside another array.
Let’s say we want to create a salary data structure with multiple employees. We can use either of the following methods:
Method 1 (Using Separate 1D Arrays):
JavaScript
let arr1 = ["ABC", 24, 18000];
let arr2 = ["EFG", 30, 30000];
let arr3 = ["IJK", 28, 41000];
let arr4 = ["EFG", 31, 28000];
let arr5 = ["EFG", 29, 35000];
// Combine the individual arrays into a multidimensional array
let salary = [arr1, arr2, arr3, arr4, arr5];
Method 2 (Using Array Literals):
JavaScript
let salary = [
["ABC", 24, 18000],
["EFG", 30, 30000],
["IJK", 28, 41000],
["EFG", 31, 28000]
];
Accessing Elements in a Multidimensional Array:
salary[0][2]
retrieves the salary of the person with the name “ABC” (which is 18000).salary[3][2]
retrieves the salary of the person with the name “EFG” (which is 28000).
for (let i = 0; i < salary.length; i++) {
for (let j = 0; j < salary[i].length; j++) {
console.log(salary[i][j]);
}
}
Adding Elements to a Multidimensional Array:
// Using square bracket notation
salary[3][3] = "India"; // Adds "India" at the 4th index of the 4th sub-array
// Using push() method
salary[3].push("India", "Mumbai"); // Adds "India" and "Mumbai" to the 4th sub-array
Remember that multidimensional arrays in JavaScript are essentially arrays inside another array, allowing you to organize data in a structured manner.
Test your knowledge with interactive quizzes.
Prepare for interviews with curated question sets.
Ask your coding-related doubts and get answers.
Earn certifications to enhance your resume.
Hands-on projects to improve your skills.
Test your knowledge with interactive quizzes.
Prepare for interviews with curated question sets.
Add your technical blogs and read technical topics.
Earn certifications to enhance your resume.
Hands-on projects to improve your skills.
People Also Asked |
---|