JavaScript is a versatile and powerful programming language, and one of its essential tools is the sort() method, especially when it comes to handling arrays.
In this article, we will dive deep into the JavaScript Sort method, exploring its syntax, parameters, use cases, and some important considerations.
Here are sorting examples
Understanding Array sort()
The sort() method of Array instances is designed to sort the elements of an array in place, and it returns a reference to the same array, now sorted.
By default, the sorting order is ascending, which means the elements are sorted from the lowest value to the highest value.
The sorting is based on converting the elements into strings and then comparing their sequences of UTF-16 code unit values.
It’s important to note that the time and space complexity of the sort() method can vary depending on the implementation, so performance may not be consistent across different JavaScript engines.
Syntax
array.sort()
array.sort(compareFn)
Parameters
compareFn (optional): This function allows for defining a custom sort order, specifying the relative positioning of elements within the array.
It should return a numerical value, indicating the relationship between two elements:
- Negative: If the first element should precede the second(the first needs to come before the second).
- Positive: If the first element should follow the second.
- Zero: If the elements are considered equal.
If omitted, the default behavior converts array elements to strings and sorts them based on the Unicode code point value of each character.
Return Value
The sort() method returns a reference to the original array, now sorted. It’s important to remember that the sorting is done in place, which means no copy of the array is made.
How to Use Array Sort ()
Default Sorting
If you use the sort() method without providing a compareFn, JavaScript will perform a default lexicographic sort.
In this case, all non-undefined array elements are sorted by converting them to strings and comparing the strings in UTF-16 code units order.
For example, “banana” comes before “cherry,” and numbers are sorted as strings, so “80” comes before “9.”
Custom Sorting
To perform a custom sort, you can provide a compareFn (comparison function). This function should adhere to specific rules:
It should be
- pure: The comparing part shouldn’t change what it’s comparing or anything else around it.
- stable: The comparison function should return the same result with the same pair of inputs.
- reflexive: The comparison function compareFn(a, a) should always return 0.
- anti-symmetric: If compareFn(a, b) returns a positive value, then compareFn(b, a) should return a negative value, and vice versa.
- transitive: If compareFn(a, b) and compareFn(b, c) have the same sign, then compareFn(a, c) should also have the same sign.
Following these rules ensures that the sort() method behaves correctly and consistently.
Here’s another article about the Double Question Mark (??) in JavaScript.
Examples
Let’s explore some examples to illustrate how JavaScript Sort method works:
Sorting Numeric Arrays
const numbers = [40, 1, 5, 200];
numbers.sort(); // [1, 200, 40, 5]
const compareNumbers = (a, b) => a - b; //comparison function
numbers.sort(compareNumbers); // [1, 5, 40, 200]
In this example, compareNumbers is a custom comparison function that sorts the numeric array in ascending order.
Sorting Arrays of Objects
const items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Zeros", value: 37 },
];
// Sort by value
items.sort((a, b) => a.value - b.value);
// Sort by name
items.sort((a, b) => {
const nameA = a.name.toUpperCase();
const nameB = b.name.toUpperCase();
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});
In this example, we demonstrate how to sort arrays of objects based on specific properties such as “value” and “name.”
Sorting Strings with Non-ASCII Characters
For sorting strings with non-ASCII characters (e.g., accented characters), you can use String.prototype.localeCompare() for accurate results.
const items = ["réservé","premier","communiqué","café", "adieu"];
items.sort((a, b) => a.localeCompare(b));
//[ 'adieu', 'café', 'communiqué', 'premier', 'réservé' ]
This approach ensures that strings with accented characters are sorted correctly.
Sort Stability
Starting from ECMAScript 2019 (version 10), the Array.prototype.sort method is stable.
This means that elements that compare as equal (returning 0 from the compareFn) will maintain their original order in the sorted array.
const students = [
{ name: "Alex", grade: 15 },
{ name: "Devlin", grade: 15 },
{ name: "Eagle", grade: 13 },
{ name: "Sam", grade: 14 },
];
students.sort((a, b) => a.grade - b.grade);
In the above example, students with the same grade (e.g., Alex and Devlin) will remain in the same order as they were in the original array.
This is a crucial feature for certain sorting scenarios.
Here is another interesting article that delves into the distinctions between Camel Case and Pascal Case.
Handling Sparse Arrays
The javascript sort method preserves empty slots in arrays, moving them to the end of the array. This behavior is essential to maintain the integrity of sparse arrays.
console.log(["a", "c", , "b"].sort()); // ['a', 'b', 'c', empty]
console.log([, undefined, "a", "b"].sort());
// ["a", "b", undefined, empty]
Explore another in-depth article covering the JavaScript reduce method.
Conclusion
The Array.prototype.sort() method is a fundamental tool for sorting arrays in JavaScript.
Whether you need to perform a simple lexicographic sort or a complex custom sort, understanding how to use this method effectively is essential for many programming tasks.
By following the rules for creating a custom comparison function and taking advantage of the stability introduced in ECMAScript 2019, you can confidently work with sorted arrays in your JavaScript applications.
Leave a Reply