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
Group strings starting with similar number in JavaScript
In JavaScript, you can group strings that start with the same number by extracting the first part before the decimal and comparing consecutive elements. This is useful when working with version numbers, decimal classifications, or any structured string data.
Problem Statement
Given an array of number strings like this:
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];
console.log("Input array:", arr);
Input array: [ '1.1', '1.2', '1.3', '2.1', '2.2', '3.1', '3.2', '3.3', '4.1', '4.2' ]
We need to group all strings starting with the same number into separate subarrays:
Expected output: [["1.1","1.2","1.3"],["2.1","2.2"],["3.1","3.2","3.3"],["4.1","4.2"]]
Using Array.reduce() Method
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];
const groupSimilarStarters = arr => {
return arr.reduce((acc, val, ind) => {
const firstChar = el => {
return (el || '').split('.')[0];
};
if (firstChar(val) === firstChar(arr[ind - 1])) {
acc[acc.length - 1].push(val);
} else {
acc.push([val]);
}
return acc;
}, []);
};
console.log(groupSimilarStarters(arr));
[ [ '1.1', '1.2', '1.3' ], [ '2.1', '2.2' ], [ '3.1', '3.2', '3.3' ], [ '4.1', '4.2' ] ]
How It Works
The solution uses Array.reduce() to build the grouped result:
-
Extract first character: The
firstCharfunction splits each string by '.' and returns the part before the decimal - Compare with previous: If the current string's first character matches the previous one, add it to the last subarray
- Create new group: Otherwise, create a new subarray with the current string
Alternative Approach Using Map
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];
const groupByFirstNumber = arr => {
const groups = new Map();
arr.forEach(item => {
const key = item.split('.')[0];
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(item);
});
return Array.from(groups.values());
};
console.log(groupByFirstNumber(arr));
[ [ '1.1', '1.2', '1.3' ], [ '2.1', '2.2' ], [ '3.1', '3.2', '3.3' ], [ '4.1', '4.2' ] ]
Comparison
| Method | Time Complexity | Maintains Order | Readability |
|---|---|---|---|
| Array.reduce() | O(n) | Yes | Good |
| Map-based | O(n) | Yes | Better |
Conclusion
Both approaches effectively group strings by their starting number. The reduce() method is more concise, while the Map-based approach offers better readability and easier maintenance for complex grouping logic.
Advertisements
