This content originally appeared on DEV Community and was authored by MR.H
On working on a project i want to return array of names for the array of email ids i have.
const users = [
{name: 'John', email: 'john@example.com'},
{name: 'Jane', email: 'jane@example.com'},
{name: 'Bob', email: 'bob@example.com'}
];
function getNames(emailIds) {
return emailIds.map((emailId)=>{
const user = users.find((user)=>{
return user.email === emailId
});
return user?.name || emailId
})
}
As you see the above code, the time complexity is O(n*m)
. In other words, assume the emailIds
array is of size 100 and users
array size is 1000 then the above code may run 1000*100 = 100000
, so in order to reduce the iterations
function getNames(emailIds) {
const emailMap= {};
users.forEach((user)=>{
emailMap[user.email]=user.name
});
return emailIds.map((emailId)=>{
return emailMap[emailId] || emailId
})
}
This function first initializes an empty object emailMap
. It then iterates over the users array using the forEach()
method and stores each email-to-name mapping in the emailMap
object, where the email is the key and the name is the value.
Now the time complexity is O(n+m)
. In other words, the above code may run 1000+100 = 1100
This modified approach is faster than the original version because it reduces the number of iterations needed to find a matching user object for each email ID. Instead of searching the users array for each email ID, the function only needs to perform a single iteration over the users array to create the email-to-name mappings. Subsequent lookups are done using constant-time key lookups in the emailMap object.
Thank you for reading please leave a like and share your thoughts in the comment section.
This content originally appeared on DEV Community and was authored by MR.H
MR.H | Sciencx (2023-03-09T07:14:58+00:00) I reduced loop from 100K to 1K. Retrieved from https://www.scien.cx/2023/03/09/i-reduced-loop-from-100k-to-1k/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.