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>
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>
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!