Sorting only columns of a 2-D array in JavaScript


We are required to write a JavaScript function that takes in a two-dimensional array of integers as the only argument.

The function should sort the elements present at the column of the array in increasing or decreasing order.

For example −

If the input array is −

const arr = [
   [6, 2, 9],
   [8, 1, 4],
   [5, 3, 7]
];

Then the array should be sorted like this −

const output = [
   [8, 3, 9],
   [6, 2, 7],
   [5, 1, 4]
];

Example

Following is the code −

const arr = [
   [6, 2, 9],
   [8, 1, 4],
   [5, 3, 7]
];
const sortColumns = (arr = []) => {
   const transpose = (matrix = []) => {
      const res = [];
      for (let row = 0; row < matrix.length; row++) {
         for (let col = 0; col < matrix[row].length; col++) {
            if(!res[col]){
               res[col] = [];
            }
            res[col][row] = matrix[row][col];
         }
      }
      return res;
   };
   arr = transpose(arr);
   for (let row = 0; row < arr.length; row++) {
      arr[row].sort((a, b) => b - a);
   }
   return transpose(arr);
};
console.log(sortColumns(arr));

Output

Following is the console output −

[ [ 8, 3, 9 ], [ 6, 2, 7 ], [ 5, 1, 4 ] ]

Updated on: 23-Jan-2021

593 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements