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
Sorting string of words based on the number present in each word using JavaScript
We are required to write a JavaScript function that takes in a string that represents a sentence. Our function should sort this sentence.
Each word in the sentence string contains an integer. Our function should sort the string such that the word that contains the smallest integer is placed first and then in the increasing order.
Problem Statement
Given a string containing words with embedded numbers, we need to sort the words based on the numerical values they contain. For example, "is2 Thi1s T4est 3a" should become "Thi1s is2 3a T4est" because the numbers are in order 1, 2, 3, 4.
Solution Approach
We'll create a helper function to extract the number from each word, then use JavaScript's sort() method with a custom comparator function.
Example Implementation
const str = "is2 Thi1s T4est 3a";
const sortByNumber = (str = '') => {
// Helper function to find the number in a word
const findNumber = (s = '') => s
.split('')
.reduce((acc, val) => +val ? +val : acc, 0);
// Split string into words
const arr = str.split(' ');
// Custom sorter function
const sorter = (a, b) => {
return findNumber(a) - findNumber(b);
};
// Sort and rejoin
arr.sort(sorter);
return arr.join(' ');
};
console.log(sortByNumber(str));
Thi1s is2 3a T4est
How It Works
The findNumber function splits each word into characters and uses reduce() to find the first numeric character. The sorter function compares the extracted numbers to determine the correct order.
Alternative Approach Using Regular Expressions
const sortByNumberRegex = (str = '') => {
return str.split(' ').sort((a, b) => {
const numA = parseInt(a.match(/\d/)[0]);
const numB = parseInt(b.match(/\d/)[0]);
return numA - numB;
}).join(' ');
};
const testStr = "is2 Thi1s T4est 3a";
console.log(sortByNumberRegex(testStr));
Thi1s is2 3a T4est
Testing with Multiple Examples
const examples = [
"is2 Thi1s T4est 3a",
"4of Fo1r pe6ople g3ood th5e the2",
"T4est 3a is2 Thi1s"
];
examples.forEach(example => {
console.log(`Input: "${example}"`);
console.log(`Output: "${sortByNumber(example)}"`);
console.log('---');
});
Input: "is2 Thi1s T4est 3a" Output: "Thi1s is2 3a T4est" --- Input: "4of Fo1r pe6ople g3ood th5e the2" Output: "Fo1r the2 g3ood 4of th5e pe6ople" --- Input: "T4est 3a is2 Thi1s" Output: "Thi1s is2 3a T4est" ---
Conclusion
This solution efficiently sorts words containing numbers by extracting the numeric values and using them as sorting criteria. The regular expression approach provides a cleaner alternative for finding digits in each word.
