Sorting strings with decimal points in JavaScript


In this problem statement, our aim is to sort strings with decimal points with the help of Javascript functionalities. So for doing this task we will use the sort and map method of Javascript.

Understanding the problem statement

The problem statement is to write a function in Javascript by which we can sort the given strings with decimal points. For example if we have an array of strings like [‘3.3’, ‘4.4’, ‘2.3’, ‘1.2’] so our task is to sort the given array of strings. But for sorting these strings first we need to convert it into numbers. After converting we will sort it as [1.2, 2.3, 3.3, 4.4]. So we have sorted an array of numbers but now again we will convert the numbers into strings as [‘1.2’, ‘2.3’, ‘3.3’, ‘4.4’].

Logic for the given problem

For solving the above given problem statement we will create a function to sort the array of strings with decimal points. So first we will convert the given array of strings into an array of numbers. After we have an array of numbers then we will sort these numbers using sort and comparison function. Then we got a sorted array of numbers and again we convert these numbers into an array of strings.

Algorithm

Step 1 − Define a function called sortStrings and this function takes an argument of strings as input.

Step 2 − The above function converts every string in the array of numbers with the help of parseFloat method. This will create a new array called numbers which is containing the same numbers as the original array but as floating point numbers.

Step 3 − With the help of the sort method we will sort the numbers array in increasing order.

Step 4 − Map the numbers and convert again in string format. And show the output.

Code for the algorithm

//function to sort the array of strings
const sortStrings = (strings) => {
   const numbers = strings.map(parseFloat);
   numbers.sort((a, b) => a - b);
   const sortedStrings = numbers.map((number) => number.toString());
   return sortedStrings;
};
 
const strings = ['2.6', '1.3', '4', '1.5', '4.77', '3'];
const sortedStrings = sortStrings(strings);
console.log(sortedStrings);

Complexity

As we have used some built-in methods in our function above. So the created function has a time complexity of O(n log n) where n is the size of the given input array. Because the sort method has an average time complexity of O(n log n).

Conclusion

In Javascript we have sorted an array of strings with decimal points in this manner. This algorithm sorts in a straightforward and efficient manner. By changing the strings into numbers before sorting them.

Updated on: 18-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements