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

How to Sort a Multidimensional Array by Multiple Columns in JavaScript?

Mary-Kate Olsen
Release: 2024-10-29 20:21:29
Original
254 people have browsed it

How to Sort a Multidimensional Array by Multiple Columns in JavaScript?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template