Home >Web Front-end >JS Tutorial >How to Sort a Multi-Column Array in JavaScript by Owner Name and Publication Name?
Multi-Column Array Sorting in JavaScript
When dealing with multidimensional arrays, organizing data based on multiple criteria becomes crucial. In this case, we have an array that requires sorting by two columns: owner_name and publication_name.
To achieve this, we can leverage JavaScript's Array.sort() method with a custom sorting function. The original provided function effectively sorts the array by owner_name. However, to include publication_name as the secondary sorting criteria, we need to modify the function.
The modified function, named mysortfunction, incorporates the following logic:
This function ensures that the array is sorted first by owner_name and, in case of ties, by publication_name.
Here's the updated mysortfunction implementation:
<code class="js">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>
By utilizing this modified function with Array.sort(), you can effectively sort your multidimensional array based on multiple columns, ensuring a consistent and organized data structure.
The above is the detailed content of How to Sort a Multi-Column Array in JavaScript by Owner Name and Publication Name?. For more information, please follow other related articles on the PHP Chinese website!