Working with 2D Arrays in JavaScript

Summary: in this tutorial, you will learn how to work with a JavaScript 2D array and manipulate its elements effectively.

Introduction to 2D arrays

What is a 2D array and how is it different from a 1D array?

A 2D array is an array of arrays, meaning it is a collection of data items organized in rows and columns. It is different from a standard 1D array in that a 1D array holds a single row of data, whereas a 2D array can hold multiple rows of data. It also allows for easier searching for specific pieces of data, and address calculation is done by multiplying the size of each element with the index of the array.

How to create 2d array in JavaScript?

In JavaScript you can create one by using an array of arrays. The elements of a 2D array are accessed by using two indices, one for the row and one for the column. is there native 2d arrays in JavaScript?

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.

const arr = [
  ['John', 'Smith', '123 Main St.', '555-555-1212'],
  ['Jane', 'Doe', '456 Maple Rd.', '555-555-3434'],
  ['Mike', 'Jones', '789 Elm St.', '555-555-5678']
];
console.log(arr);

There are a number of important methods in 2d arrays, including:

Getting the dimensions

There is no built-in method in JavaScript to get the dimensions of an array, but it is possible to create a custom function to do this:

function getDimensions(arr) {
    var dimensions = [];
    var current = arr;
    while (true) {
        dimensions.push(current.length);
        if (Array.isArray(current[0])) {
            current = current[0];
        } else {
            break;
        }
    }
    return dimensions;
}
const args = [
  ['John', 'Smith', '123 Main St.', '555-555-1212'],
  ['Jane', 'Doe', '456 Maple Rd.', '555-555-3434'],
  ['Mike', 'Jones', '789 Elm St.', '555-555-5678']
];

const dem = getDimensions(args);
//[3,4]. This is a 3x4 matrix
console.log(dem)

Looping through 2d array

//Looping through matrix and consoling out values
arr.forEach((element) =>{
  element.forEach((number) =>{
      console.log(number);
  });
});

Removing elements from the JavaScript multidimensional array

Example in JavaScript

var arr = [[1,2,3,4], [5,6,7]];

arr[0].splice(1,1); // will remove 2 from arr[0]
arr[1].splice(0,2); // will remove 5,6 from arr[1]

console.log(arr); // outputs [ [ 1, 3, 4 ], [] ]
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
// 11
// 12
// 13
// 14
// 15
var arr = [[1,2,3,4], [5,6,7]];
 
arr[0].splice(1,1); // will remove 2 from arr[0]
arr[1].splice(0,2); // will remove 5,6 from arr[1]
 
console.log(arr); // outputs [ [ 1, 3, 4 ], [] ]

How to access and modify elements in a 2D array.

To access and modify elements in a 2D array in JavaScript, one can use the length property of the array to access the last element[1], as well as the isArray() function to determine if an array is an array.

For example, to access the element at row 0, column 2, one could use the following code:

if (Array.isArray(matrix) && matrix.length > 0) {
  const element = matrix[0][2];
  // do something with element
}

Additionally, one can use the fill() and filter() functions to fill and filter elements in an array respectively. To create a 2D array, one can insert arrays into another array.

For example, to create a 3×3 matrix, one could use the following code:

let matrix = [];
for (let i = 0; i < 3; i++) {
  let row = [];
  for (let j = 0; j < 3; j++) {
    row.push(i * 3 + j);
  }
  matrix.push(row);
}

Common operations on 2D arrays, such as transposing, flipping, or rotating the array.

Transposing

Swapping the rows and columns of a 2D array, so that the row elements become the column elements and vice versa.

// Transpose
function transpose(arr) {
  let row = arr.length;
  let col = arr[0].length;
  let result = [];
  for(let i = 0; i < col; i++) {
    let newArr = [];
    for(let j = 0; j < row; j++) {
      newArr.push(arr[j][i]);
    }
    result.push(newArr);
  }
  return result;
}

Flipping:

Flipping a 2D array along its horizontal or vertical axis, so that the elements in the array are mirrored.

// Flip Vertical
function flipVertical(arr) {
  let row = arr.length;
  let col = arr[0].length;
  for(let i = 0; i < row; i++) {
    for(let j = 0; j < col / 2; j++) {
      let temp = arr[i][j];
      arr[i][j] = arr[i][col - 1 - j];
      arr[i][col - 1 - j] = temp;
    }
  }
  return arr;
}

Rotating

Rotating a 2D array by 90, 180, or 270 degrees, so that the elements in the array are rearranged accordingly.

// Rotate 90
function rotate90(arr) {
  let row = arr.length;
  let col = arr[0].length;
  let result = [];
  for(let i = 0; i < col; i++) {
    let newArr = [];
    for(let j = 0; j < row; j++) {
      newArr.push(arr[row - 1 - j][i]);
    }
    result.push(newArr);
  }
  return result;
}

Best practices for working with 2D arrays in JavaScript

Such as choosing an appropriate data structure for your use case, or optimizing the performance of your code. Best practices for working with 2D arrays in JavaScript include creating an array of one-dimensional array objects, using the special syntax for a 2D array, and using methods such as creating an array of arrays or a matrix of rows and columns.

Creating an array of one-dimensional array objects

let array2D = [];

for (let i = 0; i < 3; i++) {
  array2D[i] = [];
  for (let j = 0; j < 3; j++) {
    array2D[i][j] = i + j;
  }
}

console.log(array2D); // [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

In this example, we create an empty array called array2D and then use a nested loop to populate it with one-dimensional array objects. The outer loop runs 3 times, and the inner loop runs 3 times for each iteration of the outer loop, resulting in a total of 9 elements in the 2D array.

Using the special syntax for a 2D array

let array2D = [  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8]
];

console.log(array2D); // [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

In this example, we use the special syntax for creating a 2D array by enclosing each row of the array in brackets and separating them with commas.

Creating an array of arrays:

let array1D = [0, 1, 2, 3, 4, 5, 6, 7, 8];
let array2D = [];

while (array1D.length) {
  array2D.push(array1D.splice(0, 3));
}

console.log(array2D); // [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

In this example, we start with a one-dimensional array and use the push and splice methods to create an array of arrays. We use the push method to add elements to the array2D array, and we use the splice method to remove elements from the array1D array and add them to the array2D array in groups of 3.

Creating a matrix of rows and columns

let rows = 3;
let columns = 3;
let array2D = [];

for (let i = 0; i < rows; i++) {
  array2D[i] = [];
  for (let j = 0; j < columns; j++) {
    array2D[i][j] = i + j;
  }
}

console.log(array2D); // [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

In this example, we use a nested loop to create a matrix of rows and columns. The outer loop runs 3 times, and the inner loop runs 3 times for each iteration of the outer loop, resulting in a 2D array with 3 rows and 3 columns.

Conclusion

2D and multi-dimensional arrays are important because they allow you to store and manipulate data in a structured and organized way. They are particularly useful when you need to work with data that has multiple dimensions, such as a spreadsheet or a grid of values.

For example, you might use a 2D array to store a table of data with rows and columns, where each element in the array represents a cell in the table. You could use a multi-dimensional array to store data for a 3D model or a set of images with multiple channels (such as red, green, and blue channels for a color image).

In addition to organizing data, 2D and multi-dimensional arrays can also make it easier to perform operations on the data. For example, you can use loops to iterate over the elements of the array and apply a certain operation to each element, or you can use built-in methods such as map and filter to manipulate the data in a more concise and efficient way.

Overall, 2D and multi-dimensional arrays are a powerful tool for storing and manipulating data in JavaScript and other programming languages.

Questions involving Multidimensional arrays:

Related

How to 10x Your LLM Prompting With DSPy

Tired of spending countless hours tweaking prompts for large...

Google Announces A Cost Effective Gemini Flash

At Google's I/O event, the company unveiled Gemini Flash,...

WordPress vs Strapi: Choosing the Right CMS for Your Needs

With the growing popularity of headless CMS solutions, developers...

JPA vs. JDBC: Comparing the two DB APIs

Introduction The eternal battle rages on between two warring database...

Meta Introduces V-JEPA

The V-JEPA model, proposed by Yann LeCun, is a...

Subscribe to our AI newsletter. Get the latest on news, models, open source and trends.
Don't worry, we won't spam. 😎

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Lusera will use the information you provide on this form to be in touch with you and to provide updates and marketing.