- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting strings with decimal points in JavaScript
Suppose, we have an array of strings like this −
const arr = [ '.0', '.1', '.2', '.4', '.2.1', '.3', '.4.1', '.5', '.5.1.5' ];
We are required to write a JavaScript function that takes in one such array. Our function should simply sort the array in increasing order (as seen by a layman).
This means that strings with '.0', followed by '.1's, followed by '.2's, and so on. Therefore, after being sorted, the array should look like −
const output = [ '.0', '.1', '.2.1', '.2, '.3', '.4', '.4.1', '.5', '.5.1.5' ];
Example
The code for this will be −
const arr = [ '.0', '.1', '.2', '.4', '.2.1', '.3', '.4.1', '.5', '.5.1.5' ]; const compare = (a, b) => { if (a === b) { return 0 }; const aArr = a.split("."), bArr = b.split("."); for (let i = 0; i < Math.min(aArr.length, bArr.length); i++) { if (parseInt(aArr[i]) < parseInt(bArr[i])) { return -1 }; if (parseInt(aArr[i]) > parseInt(bArr[i])) { return 1 }; } if (aArr.length < bArr.length) { return -1 }; if (aArr.length > bArr.length) { return 1 }; return 0; }; arr.sort(compare); console.log(arr);
Output
And the output in the console will be −
[ '.0', '.1', '.2', '.2.1', '.3', '.4', '.4.1', '.5', '.5.1.5' ]
- Related Articles
- How to convert array of decimal strings to array of integer strings without decimal in JavaScript
- Sorting array of strings having year and month in JavaScript
- Sorting binary string having an even decimal value using JavaScript
- Sorting a Strings in Java
- Sorting Array with JavaScript reduce function - JavaScript
- Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript
- Sorting 2-D array of strings and finding the diagonal element using JavaScript
- Printing the correct number of decimal points with cout in C++
- Relative sorting in JavaScript
- Reversing strings with a twist in JavaScript
- Generate Ranking with combination of strings in JavaScript
- Group strings starting with similar number in JavaScript
- Alphanumeric sorting using JavaScript
- Advanced sorting in MySQL to display strings beginning with J at the end even after ORDER BY
- Sorting or Arranging an Array with standard array values - JavaScript

Advertisements