Reshaping 2-D array in JavaScript

In JavaScript, reshaping a 2-D array means converting it to a new matrix with different dimensions while preserving the original element order. This is useful for data manipulation and matrix operations.

Problem Statement

We need to write a JavaScript function that takes a 2-D array and reshapes it into a new matrix with specified rows and columns. The elements should maintain their row-traversing order from the original array.

For example, if we have:

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

The row-traversing order is [6, 7, 8, 9], and we want to reshape it into a 1×4 matrix:

[[6, 7, 8, 9]]

Solution

The key insight is that reshaping is only possible when the total number of elements remains the same. We flatten the original array and then rebuild it with new dimensions.

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

const reshapeArray = (arr, r, c) => {
    // Check if reshaping is possible
    if (r * c !== arr.length * arr[0].length) {
        return arr; // Return original if impossible
    }
    
    const result = [];
    let currentRow = [];
    
    // Flatten and reshape in one pass
    arr.forEach(row => {
        row.forEach(num => {
            currentRow.push(num);
            if (currentRow.length === c) {
                result.push(currentRow);
                currentRow = [];
            }
        });
    });
    
    return result;
};

console.log(reshapeArray(arr, r, c));
[ [ 6, 7, 8, 9 ] ]

Example with Different Dimensions

Let's reshape a 2×2 matrix into a 4×1 matrix:

const matrix = [
    [1, 2],
    [3, 4]
];

console.log("Original:", matrix);
console.log("Reshaped to 4×1:", reshapeArray(matrix, 4, 1));
console.log("Reshaped to 1×4:", reshapeArray(matrix, 1, 4));
Original: [ [ 1, 2 ], [ 3, 4 ] ]
Reshaped to 4×1: [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]
Reshaped to 1×4: [ [ 1, 2, 3, 4 ] ]

Alternative Approach Using flat()

For a more concise solution, we can use the flat() method:

const reshapeArrayFlat = (arr, r, c) => {
    const totalElements = arr.length * arr[0].length;
    
    if (r * c !== totalElements) {
        return arr;
    }
    
    const flattened = arr.flat();
    const result = [];
    
    for (let i = 0; i < r; i++) {
        result.push(flattened.slice(i * c, (i + 1) * c));
    }
    
    return result;
};

const testArray = [[1, 2, 3], [4, 5, 6]];
console.log("Original:", testArray);
console.log("Reshaped to 3×2:", reshapeArrayFlat(testArray, 3, 2));
Original: [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
Reshaped to 3×2: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]

Key Points

  • Reshaping is only possible when r × c = original_rows × original_columns
  • Elements maintain their row-traversing order from the original array
  • If reshaping is impossible, return the original array unchanged
  • The flat() method provides a cleaner approach for modern JavaScript environments

Conclusion

Reshaping 2-D arrays in JavaScript involves flattening the original array and rebuilding it with new dimensions. Always validate that the total number of elements remains constant before attempting the reshape operation.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements