Ask Your Question

Revision history [back]

To transform a one-dimensional array to a multi-dimensional array separated by commas and semicolons in Node.js, you can use the following code:

const arr = [1, 2, 3, 4, 5, 6];
const rows = 2; // Number of rows in the multi-dimensional array
const cols = 3; // Number of columns in the multi-dimensional array

const multiArr = [];
for (let i = 0; i < rows; i++) {
  const row = [];
  for (let j = 0; j < cols; j++) {
    const val = arr[i * cols + j];
    row.push(val);
  }
  multiArr.push(row.join(', '));
}

console.log(multiArr.join('; ')); // Output: "1, 2, 3; 4, 5, 6"

In this code, we define our one-dimensional array (arr) and the dimensions of our desired multi-dimensional array (rows and cols). We then create an empty array multiArr that will hold the result.

We use two nested for loops to iterate over each element of the multi-dimensional array. We calculate the index of the corresponding element in arr using the formula i * cols + j, where i and j are the current row and column indices.

We push each element into a row array and convert it to a comma-separated string using the join method. We then push the row string into the multiArr array.

Finally, we join all the rows together using semicolons and output the resulting string.