"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Perform Stable Sorting in JavaScript to Maintain Element Order Consistency?

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

Published on 2024-11-08
Browse:756

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

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);
};

Example Usage

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 }]

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

Release Statement This article is reprinted at: 1729255218 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3