Ask Your Question
0

How can I change an array to a multi-dimensional array separated by commas and semicolons in nodejs?

asked 2022-07-14 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-11 01:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-14 11:00:00 +0000

Seen: 12 times

Last updated: Aug 11 '21