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
Merging subarrays in JavaScript
This problem demonstrates how to merge subarrays containing email data by grouping emails under the same person's name. We'll use JavaScript's Set data structure to eliminate duplicates and organize the data efficiently.
Understanding the Problem
Given an array of subarrays where each subarray contains a person's name followed by their email addresses, we need to merge all emails belonging to the same person into a single subarray. For example, if "Ayaan" appears in multiple subarrays with different emails, we should combine all of Ayaan's emails into one subarray.
Algorithm
Step 1 ? Create a function that takes an array of subarrays as input.
Step 2 ? Use an object to store each person's emails, with names as keys and Sets as values to automatically handle duplicates.
Step 3 ? Iterate through each subarray, extracting the name and emails.
Step 4 ? For each person, add their emails to the corresponding Set in our data structure.
Step 5 ? Convert the organized data back into the required array format with sorted emails.
Implementation
// Create an array with name and email data
const arr = [
["Ayaan", "ayaanshri@email.com", "ayaan00@email.com"],
["Maahi", "maahibhatt@email.com"],
["Ayaan", "ayaansss@email.com", "ayaan_nepal@email.com"],
["Maahi", "maahi@email.com"]
];
// Define function to merge subarrays
function mergeSubArray(arr) {
const emailData = {};
// Process each subarray
for (let i = 0; i < arr.length; i++) {
const name = arr[i][0]; // First element is the name
const emails = arr[i].slice(1); // Remaining elements are emails
// Initialize Set for new names, or add to existing Set
if (!emailData.hasOwnProperty(name)) {
emailData[name] = new Set(emails);
} else {
emails.forEach(email => emailData[name].add(email));
}
}
// Convert back to array format with sorted emails
const result = [];
for (const [name, emailSet] of Object.entries(emailData)) {
result.push([name, ...[...emailSet].sort()]);
}
return result;
}
console.log(mergeSubArray(arr));
[
[
'Ayaan',
'ayaan00@email.com',
'ayaan_nepal@email.com',
'ayaanshri@email.com',
'ayaansss@email.com'
],
[ 'Maahi', 'maahi@email.com', 'maahibhatt@email.com' ]
]
How It Works
The algorithm uses JavaScript's Set data structure to automatically handle duplicate emails. When we encounter a name for the first time, we create a new Set containing their emails. For subsequent occurrences of the same name, we add new emails to the existing Set, which naturally eliminates duplicates.
Alternative Approach Using Map
function mergeSubArrayWithMap(arr) {
const emailMap = new Map();
arr.forEach(subarray => {
const [name, ...emails] = subarray;
if (emailMap.has(name)) {
emails.forEach(email => emailMap.get(name).add(email));
} else {
emailMap.set(name, new Set(emails));
}
});
return Array.from(emailMap.entries()).map(([name, emailSet]) =>
[name, ...Array.from(emailSet).sort()]
);
}
console.log(mergeSubArrayWithMap(arr));
[
[
'Ayaan',
'ayaan00@email.com',
'ayaan_nepal@email.com',
'ayaanshri@email.com',
'ayaansss@email.com'
],
[ 'Maahi', 'maahi@email.com', 'maahibhatt@email.com' ]
]
Time and Space Complexity
The time complexity is O(n log n), where n is the total number of email addresses. The main operations are Set additions (O(1) average) and sorting emails (O(k log k) for k emails per person). The space complexity is O(n) to store all unique emails in Sets and the final result array.
Conclusion
Merging subarrays by grouping related data is efficiently handled using JavaScript's Set data structure to eliminate duplicates. This approach provides a clean solution for consolidating email addresses under common names while maintaining sorted output.
