DEV Community

Cover image for Mastering JavaScript: Multiple Ways to Generate a Two-Dimensional Array
yanhaijing
yanhaijing

Posted on

Mastering JavaScript: Multiple Ways to Generate a Two-Dimensional Array

I often ask in interviews: Can you generate a two-dimensional array using JavaScript? This question might seem simple, but it actually reveals the interviewee's proficiency with JavaScript. Just as there are various methods to achieve the same goal, there are also various methods to generate a two-dimensional array. Today, let's explore the answers behind this question and uncover the secrets of generating two-dimensional arrays.

Knowing different methods not only allows us to handle different scenarios more adeptly but also showcases our deep understanding of JavaScript during interviews. After all, in the world of programming, being adaptable is often more important than rote memorization.

I recommend that while reading this article, try to think about how you would implement each method yourself before looking at the solution. This approach will yield more insights.

Creating a One-Dimensional Array

Before we tackle two-dimensional arrays, let's learn how to create a one-dimensional array. There are several ways to do this; here are some common methods:

1.Array Literals

This is the simplest way to create an array, just using square brackets [].

let arr = [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

2.Using the Array Constructor

The above array can also be created using the Array constructor.

let arr = new Array(1, 2, 3);
Enter fullscreen mode Exit fullscreen mode

However, when using the Array constructor, it's important to note that if only one parameter is passed, it denotes the length of the array. To create an array with a single element, in addition to the above method, you can also use the Array.of() method. When multiple parameters are present, Array.of and the Array constructor have the same effect.

let arr = Array.of(2);
console.log(arr); // [2]
Enter fullscreen mode Exit fullscreen mode

You can use this Array constructor to create an array of a specified length. But it's important to note that the elements of the array created this way are empty slots, not undefined.

let arr = new Array(3);
console.log(arr); // [empty ร— 3]
Enter fullscreen mode Exit fullscreen mode

To avoid the issue of empty slots, you can combine this with the Array.fill() method to populate the array:

let arr = new Array(3).fill(0);
console.log(arr); // [0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

3.Using Array.from()

The Array.from() method can create a new array instance from an array-like or iterable object. It can also take a map function as a second argument to initialize array elements.

let arr = Array.from({ length: 3 }, () => 0);
console.log(arr); // [0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

4.Using Spread Operator and Array()

You can combine the spread operator (...) with the Array() constructor to create and initialize an array.

let arr = [...Array(3)].map(() => 0);
console.log(arr); // [0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

Mastering these methods for creating one-dimensional arrays can help us more flexibly handle various programming scenarios. In the following sections, we'll explore how to extend these methods to create two-dimensional arrays.

Introduction to Two-Dimensional Arrays

A two-dimensional array, as the name suggests, is an array of arrays. In JavaScript, it can be used to represent matrices, grids, or any data structure that requires rows and columns. Imagine a chessboard, where each row is an array, and the entire chessboard is a two-dimensional array.

Two-dimensional arrays often appear in programming interviews, especially when dealing with matrix-related problems. For example:

  1. Matrix Related: Given an n x n two-dimensional matrix, rotate it by 90 degrees in place.
  2. Island Count: Given a two-dimensional grid composed of '1's (land) and '0's (water), calculate the number of islands.
  3. Dynamic Programming: Solve the maximum subarray sum problem.

Mastering operations on two-dimensional arrays is crucial for solving these problems, so understanding how to effectively generate and manipulate two-dimensional arrays in JavaScript is very useful.

There are many methods to generate two-dimensional arrays, and today we'll explore the following, analyzing their pros and cons:

  1. Using Nested Loops
  2. Using Array.from()
  3. Using Array.fill() and map()
  4. Using Spread Operator and map()

1.Using Nested Loops

This is the most straightforward method. First, create an outer array, then create an inner array at each position.

function create2DArray(m, n) {
  let arr = new Array(m);
  for (let i = 0; i < m; i++) {
    arr[i] = new Array(n);
    for (let j = 0; j < n; j++) {
      arr[i][j] = 0; // or other initial values
    }
  }
  return arr;
}
Enter fullscreen mode Exit fullscreen mode

Advantages: Intuitive and easy to understand.
Disadvantages: Code is somewhat verbose.

2.Using Array.from()

Array.from() can create a new array based on given parameters, and map() can process each element of the array.

function create2DArray(m, n) {
  return Array.from({ length: m }, () => Array.from({ length: n }, () => 0));
}
Enter fullscreen mode Exit fullscreen mode

Advantages: Code is more concise.
Disadvantages: May take some time for beginners to understand this syntax.

3.Using Array.fill() and map()

Similar to the previous method, but uses Array.fill() to create the initial array.

function create2DArray(m, n) {
  return Array(m)
    .fill()
    .map(() => Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

Advantages: Very concise.
Disadvantages: Similar to the previous method, it may be somewhat challenging for beginners.

4.Using Spread Operator and map()

The spread operator (...) can be used to expand an array, combined with map() to create a two-dimensional array.

function create2DArray(m, n) {
  return [...Array(m)].map(() => Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

Advantages: Code is concise and easy to understand.
Disadvantages: Performance might be slightly inferior to other methods.

Conclusion

Each method has its advantages and disadvantages, and which one you choose depends on your specific needs and personal preferences. If you value code simplicity, then using Array.from() might be a good choice. If you prefer code that is easy to understand and maintain, then using nested loops might be more suitable for you.

Mastering the various methods to generate two-dimensional arrays is an essential skill for every JavaScript developer. Through these methods, we can flexibly handle various data structures and algorithm challenges. I hope this article helps you better understand and use these techniques. Next time this question comes up in an interview, you'll be able to confidently provide an answer.

My Recommended Method

Among all the methods, I personally prefer using the Array.from() method because it's very powerful. Of course, the Array.fill method is also excellent, with the advantage of being semantic and more readable.

function create2DArray(m, n) {
  return Array.from({ length: m }, () => Array.from({ length: n }, () => 0));
}
function create2DArray(m, n) {
  return Array(m)
    .fill()
    .map(() => Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this article! Mastering the multiple ways to generate two-dimensional arrays in JavaScript can help us handle different programming challenges more effortlessly. Each method has its unique features, which one do you like best? Feel free to share your thoughts and experiences in the comments section, and let's improve together!

Top comments (15)

Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN • Edited

Another way, we can implement method 3 using Array.fill() without map

function create2DArray(m, n) {
    return Array(m).fill(Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

--UPD:

function create2DArray(m, n) {
    return Array.from({ length: m }, () => Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

This version of create2DArray uses Array.from to create a new array for each row, ensuring that each row is independent of the others. Now modifying one row won't affect the others.

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

This is incorrect. You will create an array of multiple copies of the same array:

// Create a 3x3 array
const myArray = create2DArray(3,3)

// Set 'one' item to 9
myArray[0][1] = 9

// Surprise!
console.log(myArray[0][1])  // 9
console.log(myArray[1][1])  // 9!!
console.log(myArray[2][1])  // 9!!

console.log(myArray[0] === myArray[1]) // true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yanhaijing profile image
yanhaijing

Indeed, there is this issue. Thumbs up for you!

Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN

Thank you for identifying that @jonrandy

function create2DArray(m, n) {
    return Array.from({ length: m }, () => Array(n).fill(0));
}

const myArray = create2DArray(3, 3);
myArray[0][1] = 9;

console.log(myArray[0][1]);  // 9
console.log(myArray[1][1]);  // 0
console.log(myArray[2][1]);  // 0

console.log(myArray[0] === myArray[1]); // false

console.log(myArray[1] === myArray[2]); // false
// myArray[1] and myArray[2] are different arrays, even if they contain the same values. So, myArray[1] === myArray[2] returns false.

console.log(myArray) // [[0, 9, 0], [0, 0, 0], [0, 0, 0]] 
Enter fullscreen mode Exit fullscreen mode

This version of create2DArray uses Array.from to create a new array for each row, ensuring that each row is independent of the others. Now modifying one row won't affect the others.

Thread Thread
 
yanhaijing profile image
yanhaijing

This shares a striking resemblance to Method 2 in its ingenuity.

Collapse
 
yanhaijing profile image
yanhaijing

Thank you for your feedback, this is a better approach.

Collapse
 
jimzzzz profile image
Jimmy

One more way :)

function create2DArray(m, n) {
    return [...Array(m)].map(() =>Array(n).fill(0))
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sharmi2020 profile image
Sharmila kannan

Nice article

Collapse
 
yanhaijing profile image
yanhaijing

Thank you for your support.

Collapse
 
hashirdev profile image
Hashir Afzal

Nice in depth knowledge of array and js thanks keep it up

Collapse
 
yanhaijing profile image
yanhaijing

Thank you for your support.

Collapse
 
nangegao profile image
NangeGao

NB. Did you complete the article word by word or translate it using tools?

Collapse
 
yanhaijing profile image
yanhaijing

Do you have any questions?

Collapse
 
nangegao profile image
NangeGao

Give DaLao a call !!!

Thread Thread
 
yanhaijing profile image
yanhaijing

You are the best!