From 1D to 2D: Array conversion tricks in JavaScript

Overview

In JavaScript, we often need to convert a one-dimensional array to a two-dimensional array. This kind of operation is very common in fields such as data processing and visualization. This article will introduce two methods of converting a one-dimensional array into a two-dimensional array, hoping to help readers better understand this process.

Method 1: Use a loop

The most basic approach is to use a loop to iterate through the one-dimensional array, and then insert each element into the corresponding position of the two-dimensional array. Here is a sample code using a loop:

function convertArray(arr, rows, columns) {
  var result = [];
  for (var i = 0; i < rows; i ++ ) {
    result[i] = [];
    for (var j = 0; j < columns; j ++ ) {
      var index = i * columns + j;
      if (index < arr. length) {
        result[i][j] = arr[index];
      }
    }
  }
  return result;
}

In the above code, the convertArray function receives three parameters: the original one-dimensional array arr, the number of rows in the new array rows and the columns of the new array Number of columns. The function first creates an empty two-dimensional array result, and then uses two nested loops to insert each element into its corresponding position.

In the inner loop, we calculate the index index of the current element in the one-dimensional array. If index is less than the length of the original array, the corresponding element in the original array is inserted into the current position of the two-dimensional array.

The advantage of using a loop is that the code is simple and easy to understand. However, this approach may not be efficient enough, especially for very large arrays.

Method 2: Use higher-order functions

Another way to convert a 1D array to a 2D array is to use the higher-order functions of JavaScript arrays. Here is an example code using the reduce and slice methods:

function convertArray(arr, rows, columns) {
  return arr. reduce(function(result, item, index) {
    var rowIndex = Math. floor(index / columns);
    var colIndex = index % columns;
    if (!result[rowIndex]) {
      result[rowIndex] = [];
    }
    result[rowIndex][colIndex] = item;
    return result;
  }, []);
}

In the code above, we use the reduce method to iterate over the original array arr, and then insert each element into a new two-dimensional array. In each iteration, we calculate the row and column position rowIndex and colIndex of the current element in the two-dimensional array, and then use the if statement to check the two-dimensional Whether this row already exists in the array. If it does not exist, a new row is created and the current element is inserted at the corresponding position.

The advantage of using higher-order functions is that the code is more concise, and it can improve efficiency for large arrays. At the same time, it also allows us to use higher-order functions, such as map, flatMap, etc., which can simplify the code and improve readability and maintainability. Here is an example code using the flatMap method:

function convertArray(arr, rows, columns) {
  return arr. flatMap((item, index) =>
    index % columns ? [] : [arr. slice(index, index + columns)]
  );
}

In the above code, we use the flatMap method to traverse the original array arr, and then for each element item, determine its position in the new array . If it is a new row, use the slice method to extract the elements of the row, and then return the row. Otherwise, an empty array is returned.

Example

Lituo Problem Solution Issue 13: 2022. Converting a one-dimensional array into a two-dimensional array

var construct2DArray(original, m, n) {
  const len = original. length;
  if (len !== m * n) {
    return [];
  }
  const res = new Array(m);
  for (let i = 0; i < m; i ++ ) {
    res[i] = original. slice(i * n, (i + 1) * n);
  }
  return res;
}

This function receives a one-dimensional array original, and two integers m and n. It first checks whether the length of original is equal to m * n, and returns an empty two-dimensional array if not. If the length is equal to m * n, create a two-dimensional array res, and then use the for loop to convert original Each n element is divided into a row, and finally returns the created two-dimensional array res.

This approach has a time complexity of O(mn)O(mn) and a space complexity of O(m)O(m).

var construct2DArray = function (original, m, n) {<!-- -->
    return original.length !== m * n ? [] : new Array(m).fill(0).map((v, i) => {<!-- -->
        return original. slice(n * i, n * i + n);
    });
};

This method uses the ternary operator and the array’s map() method to create a two-dimensional array. Specifically, it first checks whether the length of original is equal to m * n, and if not, returns an empty two-dimensional array [] . If the length is equal to m * n, use the map() method to create a new array of length m, each element is passed through a function It is mapped to a new array with a length of n, and the elements of the new array are extracted from original.

The second parameter of this function i represents the subscript of the currently processed element inside the map() method, which is used to calculate the starting subscript of the current line, that is, n * i. Then use the slice() method to extract the corresponding elements from original. Specifically, for line i, its elements start at n * i and end at n * i + n - 1. Therefore, you can use slice(n * i, n * i + n) to intercept the elements of this line.

This method uses the high-order function map() method of the array, the code is concise and easy to read, and the maintainability is good. The time complexity is O(mn)O(mn), and the space complexity is O(m)O(m).

var construct2DArray = function(original, m, n) {
    return original. length === m * n ?
        Array.from({ length: m }, (_, i) => original.slice(i * n, (i + 1) * n)) :
        [];
};

This method uses the Array.from() method and arrow functions to make the code more concise. Specifically, it first checks whether the length of original is equal to m * n, and if not, returns an empty two-dimensional array [] . If the length is equal to m * n, use the Array.from() method to create a new array of length m, and pass the arrow function to Each element is mapped into a new array of length n, and the elements of this new array are intercepted from original. Finally return this new 2D array.

This approach has a time complexity of O(mn)O(mn) and a space complexity of O(m)O(m).

Summary

In this article, we introduced two methods for converting a 1D array to a 2D array. The first method uses a loop, and the second uses JavaScript’s higher-order functions. The code using loops is simpler, but may not be efficient enough; the code using higher-order functions is more concise, better readable and maintainable, and has certain performance advantages for large arrays.

If you need to convert a one-dimensional array to a two-dimensional array, you can choose an appropriate method according to the actual situation. Hope this article helps you better understand array handling and transformation techniques in JavaScript.