console.log("===========Destructive approach===============")

let mat = [[10,2,5,20], [30,15,25,6], [1,3,11,6]]

function swapMat(mat) {
    for (let i = 0; i < mat.length-1; i++) {
        [mat[i][0], mat[i][mat[i].length - 1]] = [mat[i][mat[i].length - 1], mat[i][0]];
    }
    return mat
}

console.log(swapMat(mat))

console.log("===========Traverse an entire array===============")

function swapMatrix(matrix) {
    let n = matrix.length;    // Number of rows
    let m = matrix[0].length; // Number of columns

    // Loop to reverse elements in each row
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < Math.floor(m / 2); j++) {
            // Swap elements in the row
            let temp = matrix[i][j];
            matrix[i][j] = matrix[i][m - j - 1];
            matrix[i][m - j - 1] = temp;
        }
    }

    // Print the updated matrix
    for (let i = 0; i < n; i++) {
        console.log(matrix[i].join(" "));
    }

    return matrix;
}

// Initialize the 2D array (matrix)
let matrix = [
    [10, 2, 5, 20],
    [30, 15, 25, 6],
    [1, 3, 11, 9]
];

// Call the function to swap and print the matrix
swapMatrix(matrix);

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: