Sort An Array Of Arrays In JavaScript
The following approaches can be used to sort array of arrays in JavaScript.
1. Using array.sort() Method- Mostly Used
JS array.sort() is used to sort and update the original array in ascending order.
let arr = [[3, 2], [1, 4], [2, 5], [2, 0]];
arr.sort();
console.log(arr);
Output
[ [ 1, 4 ], [ 2, 0 ], [ 2, 5 ], [ 3, 2 ] ]
By default it sorts the element by first index. In case, first elements are equal, it compares the following elements and sort accordingly.
Sorting by a Specific Column
To sort an array of arrays by a specific column, you need to provide a custom comparator function to sort() that specifies which index in the sub-arrays should be compared.
let arr = [[3, 2], [1, 4], [2, 5], [5, 1]];
arr.sort((a, b) => a[1] - b[1]);
console.log(arr);
Output
[ [ 5, 1 ], [ 3, 2 ], [ 1, 4 ], [ 2, 5 ] ]
2. Using Bubble Sort Algorithm
Bubble Sort is a simple comparison based algorithm where adjacent elements are compared and they are swapped if they are in the wrong order. This process repeats for all elements in the array until it is fully sorted.
You can refer to this article: Bubble sort for Array sorting
3. Using Selection Sort Algorithm
Selection Sort works by finding the smallest (or largest) element in the array and moving it to its correct position. This repeats for each position in the array until it is sorted.
You can refer to this article: Selection sort for Array sorting
4. Using Insertion Sort Algorithm
Insertion Sort is a simple sorting algorithm where each element is placed in its correct position relative to the elements already sorted. It works by gradually building up a sorted portion of the array.
You can refer to this article: Insertion sort for Array sorting