Group Strings Starting with Similar Number in JavaScript
Last Updated :
15 May, 2024
Given an array of strings containing numbers at the beginning, the task is to group strings that start with the same number together.
Examples:
Input: arr = ["101apple", "202banana", "101orange", "303grape", "202mango", "101kiwi"];
Output: [["101apple", "101orange", "101kiwi"],["202banana", "202mango"],["303grape"]]
Explanation: In this example, the input array contains strings starting with numbers 101, 202, and 303. After grouping, we have:
Group 1: Strings starting with 101 - ["101apple", "101orange", "101kiwi"]
Group 2: Strings starting with 202 - ["202banana", "202mango"]
Group 3: Strings starting with 303 - ["303grape"]
Input: arr = ["123apple", "456banana", "123orange", "789grape", "456mango", "123kiwi"];
Output: [["123apple", "123orange", "123kiwi"], ["456banana", "456mango"], ["789grape"]]
Below are the approaches to group strings starting with similar numbers which are as follows:
Using hashmap
We can use a HashMap to group strings based on their starting numbers. First we iterate through the array of strings, extract the starting number from each string, and use it as a key in the hashmap. If the key doesn't exist, we initialize it with an empty array. After that we push the string into the array corresponding to its starting number. Finally, we return an array containing arrays of grouped strings.
Example: Implementation of program to group strings starting with similar number using HashMap
JavaScript
const groupByStartingNum = (arr) => {
const hash = {};
arr.forEach(str => {
const num = parseInt(str);
if (!isNaN(num)) {
if (!hash[num]) hash[num] = [];
hash[num].push(str);
}
});
return Object.values(hash);
};
const arr =
["123apple", "456banana", "123orange", "789grape", "456mango", "123kiwi"];
const grouped = groupByStartingNum(arr);
console.log("Grouped strings:", grouped);
Output:
Grouped strings: [
[ '123apple', '123orange', '123kiwi' ],
[ '456banana', '456mango' ],
[ '789grape' ]
]
Time Complexity: O(N), where n is the number of strings in the input array.
Auxiliary Space: O(N), where n is the number of strings in the input array.
Sorting Strings
In this approach, we sort the array of strings based on their starting numbers and then we iterate through the sorted array and group consecutive strings with the same starting number.
Example: Implementation of program to group strings starting with similar number using sorting strings approach
JavaScript
function groupBySorting(arr) {
arr.sort((a, b) => parseInt(a) - parseInt(b));
const grouped = [];
let group = [];
for (let i = 0; i < arr.length; i++) {
if (i === 0 || arr[i][0] === arr[i - 1][0]) {
group.push(arr[i]);
} else {
grouped.push(group);
group = [arr[i]];
}
}
if (group.length > 0) grouped.push(group);
return grouped;
}
const arr =
["123apple", "456banana", "123orange", "789grape", "456mango", "123kiwi"];
const groupedStrings = groupBySorting(arr);
console.log("Grouped strings:", groupedStrings);
Output:
Grouped strings: [
[ '123apple', '123orange', '123kiwi' ],
[ '456banana', '456mango' ],
[ '789grape' ]
]
Time Complexity: O(NLog N),where n is the number of strings in the input array.
Auxiliary Space: O(N)
Similar Reads
Reverse Words Starting with Particular Characters using JavaScript
We need to create a JavaScript function that reverses the order of all words in a given sentence that begins with a specific character. JavaScript allows us to reverse the words in a sentence that start with specific letters. Examples: Input: str= "I like to cook delicious meals every day"Character
4 min read
JavaScript Program to Convert a String to Roman Numerals
In this article, we will see how to convert a string to Roman numerals using JavaScript. Converting a string to Roman numerals in JavaScript is a common task when working with text data containing numeric values in Roman numeral format. Roman numerals are a numeral system used in ancient Rome, and t
4 min read
Count & Say Problem using JavaScript
The Count-and-Say problem involves generating the nth term of the count-and-say sequence. Each term of the sequence is generated from the previous term by reading the previous term and counting the number of consecutive same digits. Example:Input: n = 4;Output: 1211Explanation: We will start from 1,
2 min read
Find the Repeating & Missing Numbers in JavaScript Array ?
JavaScript allows us to find the repeating and missing number in a given array which includes numbers from 1 to N range. We are given an array that has numbers present from 1 to N range, where N is any natural number. One number is present two times and one number is missing from the range. We have
3 min read
JavaScript Program to Find Neon Number in a Range
A Neon number is a number where the sum of digits of the square of the number is equal to the number itself. For example, 9 is a Neon number because 9^2 = 81 and the sum of digits of 81 is 8 + 1 = 9, which is the number itself. We want to find all the Neon numbers within a given range. Below are the
3 min read
JavaScript Program to Get a Non-Repeating Character From the Given String
In JavaScript, we can find the non-repeating character from the input string by identifying the characters that occur only once in the string. There are several approaches in JavaScript to get a non-repeating character from the given string which are as follows: Table of Content Using indexOf and la
3 min read
How to Convert Char to String in JavaScript ?
In the article, we are going to learn about conversion Char to a string by using JavaScript, Converting a character to a string in JavaScript involves treating the character as a string, a character is a single symbol or letter, while a string is a sequence of characters. Strings can contain multipl
3 min read
Least Frequent Character in String in JavaScript
In JavaScript, finding the least frequent character in a string involves identifying the character that occurs the fewest times within the given string by iterating through the string, counting the occurrences of each character, and determining the one with the minimum frequency. This algorithmic ta
2 min read
Javascript Program to Convert Integer to Roman Numerals
Given an Integer number, the task is to convert the Integer to a Roman Number in JavaScript. Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the Late Middle Ages. Table of Content Using a Lookup ObjectUsing
2 min read
JavaScript Program to Count the Occurrences of a Specific Character in a String
In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript. Example: Input : S = âgeeksforgeeksâ and c = âeâOutput : 4Explanation: âeâ appears four times in str
3 min read