# LeetCode: Reshape the Matrix Solution

*Flat, reverse, and pop*

## Approach

Steps:

- init new matrix
- flatten the input matrix, and reverse it
- pop each of the reversed flatten matrix into each of the new matrix element

## Implementation

1/**2 * @param {number[][]} mat3 * @param {number} r4 * @param {number} c5 * @return {number[][]}6 */7var matrixReshape = function (mat, r, c) {8 const [m, n] = [mat.length, mat[0].length]910 if (m * n !== r * c) {11 return mat12 }1314 const newMatrix = Array.from({ length: r }, _ => Array(c))15 const reversedFlattenMatrix = mat.flat().reverse()1617 for (let row = 0; row < r; row++) {18 for (let col = 0; col < c; col++) {19 newMatrix[row][col] = reversedFlattenMatrix.pop()20 }21 }2223 return newMatrix24}

## Comments

Loading comments...

## Tags

leetcode

array

matrix

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.