# Using JavaScript Sort in Different Ways

JavaScript Array.prototype.sort() is a method to sort the elements of an array in place and return the sorted array. It basically converts all the elements into strings then sort by comparing their sequences of UTF-16 code unit values.

Space and time complexity of the sort method cannot be determined unless and until it is implemented. The default sort order in Javascript is Ascending.

Before diving into the tutorial, let us see the basic implementation of sort method.

arr = ['hello', 'world', 'javascript', 'is', 'fun'] console.log(arr.sort()) arr = [14, 12, 5, 1, 30, 29] console.log(arr.sort()) arr = [14, 12, 'javascript', 'is', 'fun', 1, 30, 'world', 29, 'hello'] console.log(arr.sort())

Output

["fun", "hello", "is", "javascript", "world"] [1, 12, 14, 29, 30, 5] [1, 12, 14, 29, 30, "fun", "hello", "is", "javascript", "world"]

You can notice that the numbers aren’t sorted properly. This is because of that conversion into the string which is explained earlier. To avoid this, we have to provide a comparator function to the *sort()* method. Usually, the comparator function takes 2 arguments, say *current* and *next, *to denote the current index value and next index value respectively.

arr = [14, 12, 5, 1, 30, 29] arr.sort((current, next) => { return current - next }) console.log(arr)

Output

[1, 5, 12, 14, 29, 30]

For more information, please refer to the official documentation.

Now let’s move on to our tutorial.

**Sorting 2-Dimensional Arrays**

The sort() method cannot be directly used on arrays that have more than 1 dimension. Logical operations needed to be performed to sort them. Here we will see 3 ways of sorting 2-d arrays.

#### Sorting the array along 0 axis (row-wise)

Here we sort the 2D array along 0 axis only, that is row-wise. This is easy to implement because each row itself is stored as an array. The sample code is shown below. We iterate through the rows of the 2D array and each time, we use the *sort()* method along with the comparator function as discussed above.

arr = [[10, 17, 5, 1, 17], [50, 71, 20, 5, 50], [50, 1, 2, 9]] for(i in arr){ arr[i].sort((curr, next) => curr - next) } console.log(arr)

Output

[[1, 5, 10, 17, 17], [5, 20, 50, 50, 71], [1, 2, 9, 50]]

#### Sorting the array along 1 axis (column-wise)

Here we sort the 2D array along 1 axis only, that is column-wise. This is little tricky compared to the row-wise sort as the column-wise elements are not stored in a single array. Initially, we iterate through the 2D array. The first step is to extract the column-wise elements. We use the *map()* method which will return the elements of the particular column as an array. We sort these column elements and put them back into the array. The sample code is shown below.

function extract_column(arr, n){ return arr.map(x => x[n]) } function columnSort(){ col_arr = [] for(i in arr[0]){ col_arr.push(extract_column(arr, i).sort((curr, next) => curr - next)) } arr_new = [] for(i in col_arr[0]){ arr_new.push(extract_column(col_arr, i)) } return arr_new } arr = [[10, 17, 5, 1, 17], [50, 3, 20, 5, 50], [8, 1, 2, 9, 14]] console.log(columnSort(arr))

Output

[[ 8, 1, 2, 1, 14 ], [ 10, 3, 5, 5, 17 ], [ 50, 17, 20, 9, 50 ]]

#### Sorting the array completely (both row-wise and column-wise)

The function *arraySort() *takes a 2D-array as an argument and sorts them completely. The logic behind the implementation is that we convert the 2D-array into a single array and at the same time we store the length of each column in another array. Then we sort it using *sort() *method along with comparator function. Then using the length of each column, the single array is converted back into 2D-array and it is returned.

function arraySort(arr){ full = [] row = arr.length col = [0] for (i in arr) { col.push(arr[i].length) full.push(...arr[i]) } full.sort((curr, next) => curr - next) new_arr = [] for (i = 0; i < col.length - 1; i++) { col[i + 1] += col[i]; new_arr.push(full.slice(col[i], col[i + 1])) } return new_arr } arr = [ [10, 17, 5, 1, 17], [50, 71, 20, 5, 50], [50, 1, 2, 9] ] console.log(arraySort(arr))

Output

[[1, 1, 2, 5, 5], [9, 10, 17, 17, 20], [50, 50, 50, 71]]

### Argument Sort

In this type of sort, elements of the array are sorted, and indices of elements in the original array are placed in the sorted array. We use a dictionary to perform this functionality. The sample code is shown below.

function arg_sort(arr){ num_index = {} for(i=0; i<arr.length; i++){ if(num_index[arr[i]] == undefined){ num_index[arr[i]] = [] } num_index[arr[i]].push(i) } arr.sort((curr, next) => curr - next) new_arr = [] for(i=0; i<arr.length; i++){ new_arr.push(num_index[arr[i]][0]) num_index[arr[i]].splice(0, 1) } return new_arr } arr = [5, 8, 1, 3, 10, 9, 1] console.log(arg_sort(arr))

[2, 6, 3, 0, 1, 5, 4]

Please post your comments, doubts, queries in the comment box. Happy Learning 🙂

Also, read Using JavaScript Random in Different ways

## Leave a Reply