- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] ]
- Related Articles
- Grouping and sorting 2-D array in JavaScript
- Sorting only a part of an array JavaScript
- Sorting 2-D array of strings and finding the diagonal element using JavaScript
- Uneven sorting of array in JavaScript
- Sorting parts of array separately in JavaScript
- Alternative sorting of an array in JavaScript
- Stack 1-D arrays as columns into a 2-D array in Numpy
- Finding transpose of a 2-D array JavaScript
- Reshaping 2-D array in JavaScript
- Suppress whole columns of a 2-D array that contain masked values in Numpy
- Sorting an array of binary values - JavaScript
- Searching in a sorted 2-D array in JavaScript
- JavaScript array sorting by level
- Sorting an array of objects by an array JavaScript
- Sorting Array based on another array JavaScript

Advertisements