Sorting Multidimensional Arrays by Multiple Columns
In JavaScript, sorting an array of strings can be easily achieved using the Array.sort() function. However, for multidimensional arrays, or when sorting based on multiple criteria, a custom function is required.
Consider an array with the following structure:
[publicationID][publication_name][ownderID][owner_name]
The goal is to sort the array by owner_name and then by publication_name, which would result in owners with the same name being grouped together, and publications within each group being sorted alphabetically.
Previously, a custom sort function named mysortfunction was introduced, which sorted the array based on a single column, owner_name. To extend this function for multi-column sorting, the following modifications can be made:
<code class="javascript">function mysortfunction(a, b) { var o1 = a[3].toLowerCase(); var o2 = b[3].toLowerCase(); var p1 = a[1].toLowerCase(); var p2 = b[1].toLowerCase(); if (o1 < o2) return -1; if (o1 > o2) return 1; if (p1 < p2) return -1; if (p1 > p2) return 1; return 0; }</code>
In this updated function:
First, it compares the owner names. If they differ, the function returns -1 or 1 to signify which one should precede the other.
However, if the owner names are identical, the function proceeds to compare the publication names. In this case, it returns -1 or 1 to specify their order.
If both comparisons result in equality, the function returns 0, indicating that the two elements are equal and should retain their original order.
By sorting the array using this custom function, the goal of sorting by owner_name and then by publication_name is achieved. Owners with the same name will be grouped together, with publications within each group listed alphabetically.
The above is the detailed content of How to Sort a Multidimensional JavaScript Array by Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!