shape of array in js

Shape of Array in JavaScript

Arrays in JavaScript are used to store multiple values in a single variable. The shape of an array in JavaScript refers to the number of dimensions it has and the length of each dimension.

1D Array:

A 1D array is the simplest type of array that has only one dimension. It can be created using square brackets [] or the Array constructor.


// Creating a 1D array using square brackets
var arr1 = [1, 2, 3];

// Creating a 1D array using the Array constructor
var arr2 = new Array(1, 2, 3);

The shape of a 1D array is simply the number of elements it contains. In the above examples, both arr1 and arr2 have a shape of 3.

2D Array:

A 2D array is an array of arrays. It has two dimensions - rows and columns. It can be created using nested square brackets [] or by using the Array constructor with nested arrays.


// Creating a 2D array using nested square brackets
var arr3 = [[1, 2], [3, 4], [5, 6]];

// Creating a 2D array using the Array constructor with nested arrays
var arr4 = new Array(new Array(1, 2), new Array(3, 4), new Array(5, 6));

The shape of a 2D array is denoted using two numbers - the number of rows and the number of columns. In the above examples, both arr3 and arr4 have a shape of 3x2 (3 rows and 2 columns).

3D Array:

A 3D array is an array of 2D arrays. It has three dimensions - depth, rows, and columns. It can be created using nested square brackets and nested arrays.


// Creating a 3D array using nested square brackets
var arr5 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];

// Creating a 3D array using nested arrays
var arr6 = new Array(new Array(new Array(1, 2), new Array(3, 4)), new Array(new Array(5, 6), new Array(7, 8)));

The shape of a 3D array is denoted using three numbers - the depth, number of rows and the number of columns. In the above examples, both arr5 and arr6 have a shape of 2x2x2 (2 depths, 2 rows and 2 columns).

Conclusion:

The shape of an array in JavaScript depends on the number of dimensions it has and the number of elements in each dimension. Arrays can have any number of dimensions, but most commonly used are 1D, 2D, and 3D arrays.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe