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

Using localeCompare()

The string.localeCompare() is an inbuilt method in JavaScript that is used to compare any two elements and returns a positive number if the reference string is lexicographically greater than the compare string and a negative number if the reference string is lexicographically smaller than the compare string and zero (0) if the compare and reference strings are equivalent. 

Syntax:

referenceString.localeCompare(compareString);

Example: Implementation of program to sort strings with decimal points using localeCompare()

JavaScript
function sortStrings(arr) {
    return arr.sort((a, b) => a.localeCompare(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(nlogn)

Auxiliary Space: O(1)

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

JavaScript
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)


Contact Us