Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to form a two-dimensional array with given width (columns) and height (rows) in JavaScript ?
We are required to write a JavaScript function that takes in three arguments:
height --> no. of rows of the array width --> no. of columns of the array val --> initial value of each element of the array
Then the function should return the new array formed based on these criteria.
Method 1: Using Array.apply() with map()
This approach creates arrays using Array.apply() and fills them with map():
const rows = 4, cols = 5, val = 'Example';
const fillArray = (width, height, value) => {
const arr = Array.apply(null, { length: height }).map(el => {
return Array.apply(null, { length: width }).map(element => {
return value;
});
});
return arr;
};
console.log(fillArray(cols, rows, val));
[
[ 'Example', 'Example', 'Example', 'Example', 'Example' ],
[ 'Example', 'Example', 'Example', 'Example', 'Example' ],
[ 'Example', 'Example', 'Example', 'Example', 'Example' ],
[ 'Example', 'Example', 'Example', 'Example', 'Example' ]
]
Method 2: Using Array.from() (Modern Approach)
A cleaner approach using Array.from() with a mapping function:
const create2DArray = (width, height, value) => {
return Array.from({ length: height }, () =>
Array.from({ length: width }, () => value)
);
};
console.log(create2DArray(3, 2, 'Test'));
console.log(create2DArray(4, 3, 0));
[
[ 'Test', 'Test', 'Test' ],
[ 'Test', 'Test', 'Test' ]
]
[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]
]
Method 3: Using Array constructor with fill()
Another approach using the Array constructor with fill() and map():
const build2DArray = (width, height, value) => {
return new Array(height).fill(null).map(() =>
new Array(width).fill(value)
);
};
console.log(build2DArray(2, 3, 'Hello'));
[
[ 'Hello', 'Hello' ],
[ 'Hello', 'Hello' ],
[ 'Hello', 'Hello' ]
]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| Array.apply() with map() | Complex | Good | All browsers |
| Array.from() | Excellent | Good | ES6+ (modern) |
| Array constructor with fill() | Good | Best | All browsers |
Common Use Cases
// Game board (3x3)
const gameBoard = create2DArray(3, 3, null);
console.log('Game board:', gameBoard);
// Matrix with zeros
const matrix = create2DArray(2, 2, 0);
console.log('Matrix:', matrix);
Game board: [
[ null, null, null ],
[ null, null, null ],
[ null, null, null ]
]
Matrix: [
[ 0, 0 ],
[ 0, 0 ]
]
Conclusion
Use Array.from() for the cleanest syntax in modern environments, or Array constructor with fill() for better performance. All methods effectively create two-dimensional arrays with specified dimensions and initial values.
Advertisements
