The Wayback Machine - https://web.archive.org/web/20240910033248/https://www.geeksforgeeks.org/javascript-multidimensional-array/
Open In App

JavaScript Multidimensional Array

Last Updated : 26 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Multidimensional arrays are not directly provided in JavaScript. If we want to use anything which acts as a multidimensional array then we need to create a multidimensional array by using another one-dimensional array. So multidimensional arrays in JavaScript is known as arrays inside another array. We need to put some arrays inside an array, then the total thing is working like a multidimensional array. The array, in which the other arrays are going to insert, that array is use as the multidimensional array in our code. To define a multidimensional array its exactly the same as defining a normal one-dimensional array. 

One-Dimensional array:

let arr = []; // Empty 1D array
let arr1 = ["A", "B", "C", "D"] // 1D array contains some alphabets
let arr1 = [1, 2, 3, 4, 5] // 1D array contains some digits

Multidimensional-Dimensional array:

Method 1:

1st, need to define some 1D array
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];
// "salary" defines like a 1D array but it already contains some 1D array
let salary = [arr1, arr2, arr3, arr4, arr5];

Here arr1, arr2, …arr5 are some 1D arrays that are inside the salary array.

Method 2:

let salary = [
["ABC", 24, 18000],
["EFG", 30, 30000],
["IJK", 28, 41000],
["EFG", 31, 28000],
];

Here, the salary array works like a multidimensional array. This notations are known as array literals.

Accessing the element of the salary array:

  • To access the array element we need a simple index-based notation
// This notation access the salary of "ABC" person which is 18000, 
// [0] selects 1st row, and [2] selects the 3rd element
// of that 1st row which is 18000
salary[0][2];

// Similarly,
salary[3][2]; // Selects 28000

**This notation is used for both Method 1 and Method 2.
  • For many iteration, we need to use loop to access the elements,
// This loop is for outer array
for (let i = 0, l1 = salary.length; i < l1; i++) {

// This loop is for inner-arrays
for (let j = 0, l2 = salary[i].length; j < l2; j++) {

// Accessing each elements of inner-array
documents.write( salary[i][j] );
}
}

Adding elements in Multidimensional Array: Adding elements in multi-dimensional arrays can be achieved in two ways in inner array or outer array. The inner array can be done in two different ways.

  • Adding elements to inner array:
    • We can use simple square bracket notation to add elements in multidimensional array.
salary[3][3] = "India";

// It adds "India" at the 4th index of 4th sub-array,
// If we print the entire 4th sub-array, document.write(salary[3]);
// the output will be : ["EFG", 31, 28000, "India"]
// indexing starts from 0
  • We can use push() method to add elements in the array.
salary[3].push("India", "Mumbai");

// It add "India" at the 4th index and "Mumbai" at
// 5th index of 4th sub-array
// If we print the entire 4th sub-array,
// document.write(salary[3]);
// The output will be : ["EFG", 31, 28000, "India", "Mumbai"]
// Indexing starts from 0
  • Adding elements to outer array: It is much similar to previous methods.
salary.push(["MNO", 29, 33300]);
// This row added after the last row in the "salary" array

Removing elements in Multidimensional Array: We can use pop() methods to remove elements from inner-arrays, and also use pop() method for removing a entire inner array.

// Remove last element from 4th sub-array
// That is 28000 indexing starts from 0
salary[3].pop();

// Removes last sub-array
// That is "["EFG", 31, 28000]"
salary.pop();

Example 1: Below is the example

javascript




// Prints a simple multidimensional array in 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];
let salary = [arr1, arr2, arr3, arr4, arr5];
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}


Output

[ 'ABC', 24, 18000 ]
[ 'EFG', 30, 30000 ]
[ 'IJK', 28, 41000 ]
[ 'EFG', 31, 28000 ]
[ 'EFG', 29, 35000 ]

Example 2: Below is the example.

javascript




// Prints a simple multidimensional array in
// JavaScript with different declaration
let salary = [
    ["ABC", 24, 18000],
    ["EFG", 30, 30000],
    ["IJK", 28, 41000],
    ["EFG", 31, 28000],
];
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}


Output

[ 'ABC', 24, 18000 ]
[ 'EFG', 30, 30000 ]
[ 'IJK', 28, 41000 ]
[ 'EFG', 31, 28000 ]

Example 3: Below is the example.

javascript




// Prints a simple multidimensional array in JavaScript
// where we just print the salary of a specific person
let salary = [
    ["ABC", 24, 18000],
    ["EFG", 30, 30000],
    ["IJK", 28, 41000],
    ["EFG", 31, 28000],
];
console.log("salary of 2nd person : " + salary[1][2]);
console.log("salary of 4th person : " + salary[3][2]);


Output

salary of 2nd person : 30000
salary of 4th person : 28000

Example 4: Below is the example.

javascript




// Prints a simple multidimensional array in
// JavaScript where we add elements in the array
// using simple square bracket and push() method
let salary = [
    ["ABC", 24, 18000],
    ["EFG", 30, 30000],
    ["IJK", 28, 41000],
    ["EFG", 31, 28000],
];
 
// Prints first array
console.log("Original array :<br>");
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}
 
// Adding "India" at the 4th index of 4th sub array
salary[3][3] = "India";
 
console.log("<br>after adding \"India\" at the 4th array :<br>");
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}
 
console.log("<br>after adding \"USA\" and \"Canada\" "
    + "at the 3rd array using \"push()\" method :");
salary[2].push("USA", "Canada");
 
// Adding "USA" and "Canada" in the 2nd sub-array
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}


Output:

Original array :
ABC, 24, 18000
EFG, 30, 30000
IJK, 28, 41000
EFG, 31, 28000

after adding "India" at the 4th array :
ABC, 24, 18000
EFG, 30, 30000
IJK, 28, 41000
EFG, 31, 28000, India

after adding "USA" and "Canada" at the 3rd array using "push()" method :
ABC, 24, 18000
EFG, 30, 30000
IJK, 28, 41000, USA, Canada
EFG, 31, 28000, India

Example 5: Below is the example.

javascript




// Prints a simple multidimensional array in
// JavaScript where we add a new inner array
let salary = [
["ABC", 24, 18000],
["EFG", 30, 30000],
["IJK", 28, 41000],
["EFG", 31, 28000],
];
 
// Prints first array
console.log("Original array :");
 
for(let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}
 
console.log("After adding a new inner array :");
 
// Pushing a new sub-array
salary.push(["MNO", 29, 33300]);
 
for(let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}


Output

Original array :
[ 'ABC', 24, 18000 ]
[ 'EFG', 30, 30000 ]
[ 'IJK', 28, 41000 ]
[ 'EFG', 31, 28000 ]
After adding a new inner array :
[ 'ABC', 24, 18000 ]
[ 'EFG', 30, 30000 ]
[ 'IJK', 28, 41000 ]
[ '...

Output:

Original array :
ABC, 24, 18000
EFG, 30, 30000
IJK, 28, 41000
EFG, 31, 28000

After adding a new inner array :
ABC, 24, 18000
EFG, 30, 30000
IJK, 28, 41000
EFG, 31, 28000
MNO, 29, 33300

Example 6: Below is the example.

javascript




// Prints a simple multidimensional array in
// JavaScript where we remove a single element
// and a entire sub-array
let salary = [
    ["ABC", 24, 18000],
    ["EFG", 30, 30000],
    ["IJK", 28, 41000],
    ["EFG", 31, 28000],
];
 
// Prints first array
console.log("Original array :");
 
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}
 
console.log("After removing last element "
    + "of last inner array :");
 
// Removes the last element of 3rd sub-array
salary[3].pop();
 
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i] + "");
}
 
console.log("After removing last inner array :");
 
// Removes last sub-array
salary.pop();
 
for (let i = 0; i < salary.length; i++) {
    console.log(salary[i]);
}


Output

Original array :
[ 'ABC', 24, 18000 ]
[ 'EFG', 30, 30000 ]
[ 'IJK', 28, 41000 ]
[ 'EFG', 31, 28000 ]
After removing last element of last inner array :
ABC,24,18000
EFG,30,30000
IJK,28,41000
EFG,31
Aft...

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Similar Reads

How to Sort a Multidimensional Array in JavaScript by Date ?
Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order. Below are the possible approaches: Table of Content Using l
2 min read
Convert multidimensional array to XML file in PHP
Given a multi-dimensional array and the task is to convert this array into an XML file. To converting the multi-dimensional array into an xml file, create an XML file and use appendChild() and createElement() function to add array element into XML file. Example: First, create a PHP Multidimensional Array for converting that array into the XML file
2 min read
Converting all keys into snake case in multidimensional array in PHP
In the Snake case, we need to convert a given sentence or a word to a style of writing where all upper case characters will be replaced with lower case and all the gaps will be replaced with an underscore(_). In this article, we will see how to find the snake case of the all keys of a given array. Here, we need to check each of the elements present
4 min read
How to Build Multi Type Multidimensional Arrays in TypeScript ?
TypeScript, multi-type multidimensional Arrays allow us to create arrays that can hold elements of multiple types at each level of the array hierarchy. we will learn how to build multi-type multidimensional arrays. These are the following methods: Table of Content Using Union TypesUsing Tuple TypesUsing Interface TypesUsing GenericsUsing Union Type
3 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How to get the elements of one array which are not present in another array using JavaScript?
The task is to get the elements of one array that are not present in another array. Here we are going to use JavaScript to achieve the goal. Here are a few techniques discussed. Approach Take the arrays in variables.Use the .filter() method on the first array and check if the elements of the first array are not present in the second array, Include
2 min read
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
Consider the below codes: var myArray = new Array(5); and var myArray = [5]; Though these two lines might appear the same, but it is not the case. Consider the below explanations: Case 1: var myArray = new Array(5) This method is used to define an array of length 5. The parameter passed here '5' is an argument that defines the initial length of the
2 min read
How to check whether an array is subset of another array using JavaScript ?
The task is to check whether an array is a subset of another array with the help of JavaScript. There are a few approaches, we will discuss below: Approaches:using JavaScript array.every() methodusing JavaScript array.some() methodApproach 1: Using JavaScript array.every() methodThis approach checks whether every element of the second array is pres
2 min read
Difference between array.size() and array.length in JavaScript
The array.size() method is functionally equivalent to the array.length property and it can be only used in jQuery. Here in JavaScript array.size() is invalid method so array.length property should be used. Below examples implement the above concept: Example 1: This example demonstrates array.size() method and array.length property. C/C++ Code &lt;!
3 min read
How to write a program that takes a predicate and array, like Array.filter(), but only keeps x if pred(x) === false in JavaScript ?
The predicate in JavaScript is the same as the predicate maths which returns true or false. The predicate is just like a function that determines whether the passed arguments satisfy the given condition or not. The predicate returns only true or false. In this article, let us see the working of the predicate with arrays when it is passed with a fun
3 min read
Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Javascript Program to Check if it is possible to make array increasing or decreasing by rotating the array
Given an array arr[] of N distinct elements, the task is to check if it is possible to make the array increasing or decreasing by rotating the array in any direction.Examples: Input: arr[] = {4, 5, 6, 2, 3} Output: Yes Array can be rotated as {2, 3, 4, 5, 6}Input: arr[] = {1, 2, 4, 3, 5} Output: No Approach: There are four possibilities: If the arr
4 min read
How to create an array of elements, ungrouping the elements in an array produced by zip in JavaScript ?
We can create an array of elements by ungrouping the elements in an array produced by zip by using different methods in JavaScript such as Math.max(), array specific methods namely Array.prototype.map(), Array.prototype.reduce() and Array.prototype.forEach(). This operation can also be termed as unzip. Before looking at unzip, let us understand wha
2 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 Pair - Sum Array?A pair-sum array in JavaScript is
4 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array. Example: In thi
3 min read
How to Search Character in List of Array Object Inside an Array Object in JavaScript ?
Searching for a character in a list of array objects inside an array object involves inspecting each array object, and then examining each array within for the presence of the specified character. The goal is to determine if the character exists within any of the nested arrays. There are several ways to search for characters in a list of array obje
4 min read
Build Tree Array from Flat Array in JavaScript
To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of comments as input and returns a tree-like array of comme
7 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to convert an array of objects to a map in JavaScript:
2 min read
JavaScript Program to Transform Nested Array into Normal Array
JavaScript allows us to convert nested arrays into a single, flat array using JavaScript. By simplifying nested structures, you can enhance the manageability and readability of your code. Example: Input: [[1, 2], [3, [4, 5]]] Output: [1, 2, 3, 4, 5]Below are the approaches to transform nested arrays into normal arrays with JavaScript: Table of Cont
3 min read
What is the difference between Array.slice() and Array.splice() in JavaScript ?
In JavaScript, slice() and splice() are array methods with distinct purposes. `slice()` creates a new array containing selected elements from the original, while `splice()` modifies the original array by adding, removing, or replacing elements. slice():The slice() method in JavaScript extracts a section of an array and returns a new array containin
3 min read
Difference Between Array.prototype.map() and Array.prototype.flatMap() in JavaScript
In JavaScript, Array.prototype.map() and Array.prototype.flatMap() are both the methods used to the transform elements in arrays but they differ in their behaviors regarding handling and flattening of the nested arrays. What is Array.prototype.map()?The map() method creates a new array populated with the results of calling a provided the function o
3 min read
How to group objects in an array based on a common property into an array of arrays in JavaScript ?
In this article, we will try to understand how we may easily group objects in an array based on a common property into an array of arrays in JavaScript with the help of an example itself. Grouping objects in an array based on a common property into an array of arrays in JavaScript. Organize data by shared property for efficient data manipulation. S
6 min read
How to Sort an Array using JavaScript when Array Elements has Different Data Types ?
Sorting an array in JavaScript is the process of arranging the elements of the array in a certain order. Generally sorting in an array is to arrange the elements in increasing or decreasing order. It is a common task, however, when an array contains different data types such as numbers, strings, and booleans, sorting becomes a little more complicat
3 min read
How to move an array element from one array position to another in JavaScript?
In JavaScript, we can access an array element as in other programming languages like C, C++, Java, etc. Also, there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another we can splice() method or we can simply use array
5 min read
How to create an array of partial objects from another array in JavaScript ?
Creating an array of partial objects from another array is a useful technique in JavaScript, especially for data transformation and manipulation. This guide covers various methods to efficiently create these arrays, enhancing your ability to work with complex data structures. Importance of Creating Partial Objects:Creating partial objects is crucia
6 min read
Difference Between Array.from and Array.of in JavaScript
JavaScript provides various methods for creating and manipulating arrays, two of which are Array.from and Array.of. These methods are part of the ECMAScript 6 (ES6) specification and offer distinct ways to create arrays. Understanding the differences between these two methods is important for efficient array handling in your JavaScript code. This a
3 min read
Copy Array Items into Another Array in JavaScript
We will see how to copy array items into another array in JavaScript. This operation is valuable when you need to generate a new array containing either identical or a subset of elements from an original array. These are the following ways to solve this problem: Table of Content Using the Spread Operator (...)Using slice() MethodUsing apply() Metho
5 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing Set for Efficient FilteringUsi
3 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
8 min read