"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 Implement Stable Sorting in JavaScript for Maintaining Element Order During Sorting?

How to Implement Stable Sorting in JavaScript for Maintaining Element Order During Sorting?

Published on 2024-11-17
Browse:620

How to Implement Stable Sorting in JavaScript for Maintaining Element Order During Sorting?

Stable Sorting in JavaScript

Objective: Efficiently sort an array of objects based on a key, maintaining consistency and stability.

Algorithm Recommendation: While many sorting algorithms exist, for your specific need of stability, consider implementing a modified version of a non-stable sorting algorithm such as QuickSort or MergeSort.

Stable Sorting Technique:

To ensure stability, add an additional criterion to the sort comparison function. Specifically, when comparing two equal elements, use their original positions in the input array as a tiebreaker. This will maintain the order of elements with the same key.

JavaScript Implementation:

const stableSort = (arr, key, order) => {
  // Get initial positions of elements
  const positions = arr.map((el, i) => i);

  // Sort using modified comparison function
  arr.sort((a, b) => {
    const keyA = a[key];
    const keyB = b[key];

    if (keyA === keyB) {
      // Fall back to position for stability
      return positions[a] - positions[b];
    }

    return order === "asc" ? keyA - keyB : keyB - keyA;
  });

  return arr;
};

Example Usage:

const arr = [
  { id: 1, value: 4 },
  { id: 2, value: 2 },
  { id: 3, value: 4 },
  { id: 4, value: 3 },
];

const sortedArr = stableSort(arr, "value", "asc");

// Output:
// [
//   { id: 2, value: 2 },
//   { id: 1, value: 4 },
//   { id: 3, value: 4 },
//   { id: 4, value: 3 },
// ]

By using this technique, you can obtain stable sorting even from non-stable sorting algorithms, making it suitable for your scenario of about 200-300 objects.

Release Statement This article is reprinted at: 1729255458 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