Home > Web Front-end > JS Tutorial > body text

How to Perform Stable Sorting in JavaScript to Maintain Element Order Consistency?

Susan Sarandon
Release: 2024-10-18 20:42:03
Original
548 people have browsed it

How to Perform Stable Sorting in JavaScript to Maintain Element Order Consistency?

Stable Sorting Algorithms in JavaScript

When sorting data, preserving the original order of equal elements is crucial for stable sorting algorithms. In this context, we aim to sort an array of objects with a specific key in a given order while maintaining element order consistency.

Stable Sorting Technique

Interestingly, even non-stable sorting functions can achieve stable sorting. By capturing the initial position of each element before sorting, we can break ties in the sorting comparison using position as a secondary criterion.

Implementation in JavaScript

<code class="javascript">const sortBy = (arr, key, order) => {
  // Capture element positions
  const positions = arr.map((item, i) => {
    return { item, position: i };
  });

  // Perform sorting
  positions.sort((a, b) => {
    let cmp = a.item[key].localeCompare(b.item[key]);
    if (cmp === 0) {
      // Tiebreaker: sort by position
      cmp = a.position - b.position;
    }
    if (order === "desc") {
      return cmp * -1;
    } else {
      return cmp;
    }
  });

  // Return sorted objects
  return positions.map(position => position.item);
};</code>
Copy after login

Example Usage

<code class="javascript">const data = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Eve", age: 25 },
];

const sortedAscending = sortBy(data, "age", "asc");
console.log(sortedAscending); // [{ name: "Alice", age: 25 }, { name: "Eve", age: 25 }, { name: "Bob", age: 30 }]

const sortedDescending = sortBy(data, "age", "desc");
console.log(sortedDescending); // [{ name: "Bob", age: 30 }, { name: "Eve", age: 25 }, { name: "Alice", age: 25 }]</code>
Copy after login

This technique allows stable sorting in JavaScript, preserving the original order of elements with equal values.

The above is the detailed content of How to Perform Stable Sorting in JavaScript to Maintain Element Order Consistency?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!