Custom Comparator Function
In this approach, we write a custom comparator function that parses the strings as numbers and compares them accordingly.
Example: Implementation of program to sort strings with decimal points using Custom Comparator Function
function sortStrings(arr) {
return arr.sort((a, b) => parseFloat(a) - parseFloat(b));
}
const strings = ["2.5", "1.3", "3.2", "1.1", "2.1"];
const sorted = sortStrings(strings);
console.log("Sorted:", sorted);
Output
Sorted: [ '1.1', '1.3', '2.1', '2.5', '3.2' ]
Time Complexity: O(N Log N)
Auxiliary Space: O(1)
Sorting Strings with Decimal Points in JavaScript
Sorting strings with decimal points in JavaScript can be done using the localeCompare
method or a custom sorting function.
Examples:
Input: strings = ["2.5", "1.3", "3.2", "1.1", "2.1"]
Output: ["1.1", "1.3", "2.1", "2.5", "3.2"]
Input: ["2.7", "1.5", "3.6", "1.2", "2.1"];
Output: ["1.2", "1.5", "2.1", "2.7", "3.6"]
Table of Content
- Using localeCompare()
- Custom Comparator Function
Contact Us