Home  >  Article  >  Web Front-end  >  How to Sort a Multidimensional JavaScript Array by Multiple Columns?

How to Sort a Multidimensional JavaScript Array by Multiple Columns?

DDD
DDDOriginal
2024-10-28 23:18:30123browse

How to Sort a Multidimensional JavaScript Array by Multiple Columns?

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:

  • o1 and o2 represent the owner names in lowercase.
  • p1 and p2 represent the publication names in lowercase.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn