Sorting an Array by Multiple Columns in JavaScript
Sorting a multidimensional array based on multiple columns requires a customized sorting function. For a primary array consisting of "publicationIDownderID", the goal is to sort first by owner_name and then by publication_name.
The existing sort function provided, "mysortfunction", is limited to sorting solely by owner_name. To address this limitation, the function must be modified to consider both owner_name and publication_name:
<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>
This modified function now prioritizes sorting by owner_name. If owner names are identical, it proceeds to use publication_name as the tiebreaker for sorting.
The updated "mysortfunction" can now be used in conjunction with Array.sort() to achieve the desired multi-column sort:
<code class="javascript">array.sort(mysortfunction);</code>
The above is the detailed content of How to Sort a Multidimensional Array by Multiple Columns in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!