Reshaping 2-D array in JavaScript


Problem

We are required to write a JavaScript function that takes in a 2-D array of numbers, arr, as the first argument and two numbers, r and c, representing the row number and column number of the desired matrix, respectively.

Our function should form and return a new 2-D array with the specified rows and columns in the same row-traversing order as they were in the input array.

For example, if the input to the function is −

const arr = [
   [6, 7],
   [8, 9]
];
const r = 1, c = 4;

Then the output should be −

const output = [[6, 7, 8, 9]];

Output Explanation

The row-traversing of arr is [6, 7, 8, 9]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list

Example

Following is the code −

Live Demo

const arr = [
   [6, 7],
   [8, 9]
];
const r = 1, c = 4;
const reshapeArray = (arr, r, c) => {
   if (r * c !== arr.length * arr[0].length) {
      return arr
   }
   const res = []
   let row = []
   arr.forEach(items => items.forEach((num) => {
      row.push(num)
      if (row.length === c) {
         res.push(row)
         row = []
      }
   }))
   return res
};
console.log(reshapeArray(arr, r, c));

Output

Following is the console output −

[[6, 7, 8, 9]]

Updated on: 21-Apr-2021

623 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements