I reduced loop from 100K to 1K

mrh0200

MR.H

Posted on March 9, 2023

I reduced loop from 100K to 1K

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
   })
}
Enter fullscreen mode Exit fullscreen mode

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
   })
}
Enter fullscreen mode Exit fullscreen mode

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.

Happy Coding
💖 💪 🙅 🚩
mrh0200
MR.H

Posted on March 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related