Home > Web Front-end > JS Tutorial > How to Sort a Multi-Column Array in JavaScript by Owner and Publication Name?

How to Sort a Multi-Column Array in JavaScript by Owner and Publication Name?

DDD
Release: 2024-11-01 01:29:28
Original
515 people have browsed it

How to Sort a Multi-Column Array in JavaScript by Owner and Publication Name?

Customized Multi-Column Array Sorting in JavaScript

Sorting arrays based on multiple columns is a common task in programming. This question explores how to achieve this in JavaScript for a specific array structure.

The array in question is a multidimensional array with the following structure:

[publicationID][publication_name][ownderID][owner_name]
Copy after login

The goal is to sort the array first by owner_name and then by publication_name.

To sort on multiple columns, the custom sort function needs to consider both criteria. The following code demonstrates how to modify the provided mysortfunction to achieve the desired result:

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

In this function:

  • o1 and o2 are converted to lowercase for case-insensitive comparison of owner_name.
  • p1 and p2 are converted to lowercase for case-insensitive comparison of publication_name.
  • If the owner_name values are different, the function sorts based on them.
  • If the owner_name values are the same, the function uses the publication_name for tiebreaking.

The above is the detailed content of How to Sort a Multi-Column Array in JavaScript by Owner and Publication Name?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template