Open In App

Group Strings Starting with Similar Number in JavaScript

Last Updated : 15 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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)


Next Article

Similar Reads