Back to JavaScript
2026-04-237 min read

JavaScript Program to Create Two Dimensional Array

Learn JavaScript Program to Create Two Dimensional Array step by step with clear examples and exercises.

Why This Matters

In this comprehensive lesson, we will delve into the art of creating and manipulating two-dimensional arrays in JavaScript. Two-dimensional arrays are essential for handling complex data structures, such as tables, grids, or matrices, and are indispensable for solving real-world programming problems involving tabular data. By mastering the creation and management of two-dimensional arrays, you will be well-equipped to tackle a wide range of challenges in your coding journey.

Prerequisites

To fully grasp this lesson, it is crucial that you have a solid understanding of:

  1. JavaScript basics (variables, data types, operators)
  2. Arrays in JavaScript
  3. Loops and control structures (for loop, if-else statements)
  4. Understanding of functions and their parameters
  5. Basic knowledge of object properties
  6. Comprehension of array methods such as push(), pop(), shift(), unshift(), map(), filter(), and reduce()
  7. Familiarity with the concept of nested functions

Core Concept

A two-dimensional array in JavaScript is essentially an array of arrays, where each inner array represents a row, and the outer array holds all rows together. To create a two-dimensional array using JavaScript, we can use nested for loops to generate the required structure.

Here's an example function that creates a two-dimensional array with specified dimensions:

function createTwoDimensionalArray(rows, columns, initialValue) {
const arr = Array(rows); // creating outer array

// Initializing each element of the outer array to an empty inner array
for (let i = 0; i < rows; i++) {
arr[i] = Array(columns).fill(initialValue);
}

return arr;
}

In this example, the createTwoDimensionalArray function takes three arguments: rows, which represents the number of rows in the array, columns, which represents the number of columns, and initialValue, which sets a default value for each element. The function initializes an empty outer array and then creates inner arrays for each row using nested for loops.

Initializing a Two-Dimensional Array with Objects

If you want to create a two-dimensional array of objects instead, you can modify the createTwoDimensionalArray function like this:

function createTwoDimensionalObjectsArray(rows, columns) {
const arr = Array(rows); // creating outer array

// Initializing each element of the outer array to an empty inner object
for (let i = 0; i < rows; i++) {
arr[i] = {};
for (let j = 0; j < columns; j++) {
Object.defineProperty(arr[i], `property_${j}`, { value: null });
}
}

return arr;
}

In this example, the function creates an empty outer array and then creates inner objects for each row using nested for loops and Object.defineProperty(). We initialize each property to null, but you can replace this with any desired value or even functions if needed.

Common Mistakes

  1. Forgetting to initialize the outer array: Make sure to create an empty outer array before initializing inner arrays using nested for loops.
  2. Not defining properties correctly: When creating a two-dimensional array of objects, make sure to define each property using Object.defineProperty() or by directly assigning values to object properties.
  3. Incorrectly accessing elements: Remember that in a two-dimensional array, you can access elements using two indices: array[row][column].
  4. Not handling edge cases: Be mindful of edge cases such as empty arrays or arrays with fewer rows or columns than specified.
  5. Using the wrong data type for inner arrays: If you are creating a two-dimensional array of objects, make sure to use an object ({}) instead of an array ([]) when initializing each row.

Worked Example

Let's create a 3x3 two-dimensional array filled with numbers from 1 to 9 and print it:

function createTwoDimensionalArray(rows, columns) {
const arr = Array(rows); // creating outer array

for (let i = 0; i < rows; i++) {
arr[i] = Array(columns).fill().map((_, j) => j + 1);
}

return arr;
}

const arr = createTwoDimensionalArray(3, 3);
console.log(arr);

Output:

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]

Practice Questions

  1. Write a function that creates a 4x4 two-dimensional array filled with random numbers between 1 and 100.
  2. Write a function that finds the sum of all elements in a given two-dimensional array.
  3. Write a function that checks if a given value exists in a two-dimensional array.
  4. Write a function that sorts the objects in a two-dimensional array by one of their properties.
  5. Write a function to find the maximum element in each row and return an array containing these max values.
  6. Write a function to transpose a two-dimensional array (swap rows and columns).
  7. Write a function to find the determinant of a 2x2 matrix represented as a two-dimensional array.
  8. Write a function to count the number of occurrences of a given value in a two-dimensional array.
  9. Write a function to find the average of all elements in a two-dimensional array.
  10. Write a function to remove duplicate rows or columns based on a specified property and return a new array without duplicates.

FAQ

How can I find the sum of all elements in a given two-dimensional array?

You can use nested loops and a running total to calculate the sum of all elements in a two-dimensional array. Here's an example function:

function sumElements(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
total += arr[i][j];
}
}
return total;
}

How can I create a 5x5 two-dimensional array and initialize its elements with alternating values (1, 0, 1, 0, ...)?

You can use the createTwoDimensionalArray() function from the Core Concept section and modify the for loops to assign alternating values. Here's an example:

const rows = 5;
const columns = 5;
const arr = createTwoDimensionalArray(rows, columns);

let value = 1;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
arr[i][j] = value;
value = !value; // toggling between 1 and 0
}
}

console.log(arr);

How can I write a function that checks if a given value exists in a two-dimensional array?

You can use nested loops to check for the presence of a specific value in a two-dimensional array. Here's an example function:

function containsValue(arr, target) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] === target) {
return true;
}
}
}
return false;
}

How can I write a function to find the maximum element in each row and return an array containing these max values?

You can use nested loops and the Math.max() function to find the maximum element in each row of a two-dimensional array. Here's an example function:

function findMaxValues(arr) {
const maxValues = [];
for (let i = 0; i < arr.length; i++) {
let currentMax = -Infinity;
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] > currentMax) {
currentMax = arr[i][j];
}
}
maxValues.push(currentMax);
}

return maxValues;
}

How can I write a function to transpose a two-dimensional array (swap rows and columns)?

You can use nested loops to transpose a two-dimensional array by swapping rows and columns. Here's an example function:

function transpose(arr) {
const transposed = Array.from({ length: arr[0].length }, () => Array(arr.length).fill(null));

for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
transposed[j][i] = arr[i][j];
}
}

return transposed;
}

How can I write a function to find the determinant of a 2x2 matrix represented as a two-dimensional array?

You can use the formula for the determinant of a 2x2 matrix to calculate the determinant of a given 2x2 matrix. Here's an example function:

function determinant(arr) {
return arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0];
}

How can I write a function to sort the objects in a two-dimensional array by one of their properties?

You can use the Array.prototype.sort() method along with a custom comparator function to sort the objects in a two-dimensional array by one of their properties. Here's an example function:

function sortByProperty(arr, property) {
arr.sort((a, b) => a[property] - b[property]);
return arr;
}

How can I write a function to count the number of occurrences of a given value in a two-dimensional array?

You can use nested loops and a counter variable to count the number of occurrences of a specific value in a two-dimensional array. Here's an example function:

function countOccurrences(arr, target) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] === target) {
count++;
}
}
}
return count;
}

How can I write a function to find the average of all elements in a two-dimensional array?

You can use nested loops and a running total to calculate the sum of all elements in a two-dimensional array, and then divide by the total number of elements. Here's an example function:

function averageElements(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
total += arr[i][j];
}
}
return total / (arr.length * arr[0].length);
}

How can I write a function to find the duplicate rows or columns based on a specified property or element and remove them from the two-dimensional array?

You can use nested loops, an object to store unique elements, and array methods like filter() or forEach() to find and remove duplicates in a two-dimensional array. Here's an example function that removes duplicate rows based on a specified property:

function removeDuplicateRows(arr, property) {
const uniqueElements = {};
let uniqueArray = [];

arr.forEach((row) => {
if (!uniqueElements[row[property]]) {
uniqueElements[row[property]] = true;
uniqueArray.push(row);
}
});

return uniqueArray;
}
JavaScript Program to Create Two Dimensional Array | JavaScript | XQA Learn