Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Ordering string in an array according to a number in the string JavaScript
We have an array of strings each of which contain one or more numbers like this ?
const arr = ['di5aster', 'ca1amity', 'cod3', 'ho2me3', 'ca11ing'];
We are required to write a sorting function that sorts this array in ascending order of the numbers present in the strings. The correct order will be ?
const output = [ 'ca1amity', 'cod3', 'di5aster', 'ca11ing', 'ho2me3' ];
Therefore, let's write the code for this problem ?
Understanding the Problem
Each string contains embedded numbers. We need to extract these numbers and sort the array based on their numerical value:
- 'ca1amity' ? 1
- 'cod3' ? 3
- 'di5aster' ? 5
- 'ca11ing' ? 11
- 'ho2me3' ? 23 (concatenated digits)
Solution Using Custom Sort Function
const arr = ['di5aster', 'ca1amity', 'cod3', 'ho2me3', 'ca11ing'];
const filterNumber = str => {
return +str
.split("")
.filter(el => el.charCodeAt() >= 48 && el.charCodeAt() <= 57)
.join("");
};
const sorter = (a, b) => {
return filterNumber(a) - filterNumber(b);
};
arr.sort(sorter);
console.log(arr);
[ 'ca1amity', 'cod3', 'di5aster', 'ca11ing', 'ho2me3' ]
How It Works
The filterNumber function extracts digits from each string:
-
split("")- Converts string to character array -
filter()- Keeps only digits (ASCII codes 48-57) -
join("")- Combines digits into a string -
+operator converts the result to a number
Alternative Approach Using Regular Expressions
const arr = ['di5aster', 'ca1amity', 'cod3', 'ho2me3', 'ca11ing'];
const extractNumber = str => {
return parseInt(str.replace(/\D/g, ''), 10);
};
arr.sort((a, b) => extractNumber(a) - extractNumber(b));
console.log(arr);
[ 'ca1amity', 'cod3', 'di5aster', 'ca11ing', 'ho2me3' ]
Comparison
| Method | Readability | Performance |
|---|---|---|
| CharCode Filtering | More verbose | Slightly faster |
| Regular Expression | More concise | Slightly slower |
Conclusion
Both approaches effectively sort strings by their embedded numbers. The regular expression method is more readable, while the character code approach offers slightly better performance for large datasets.
Advertisements
