Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript reduce taking too much time to convert array into object

I have 2 lists of array. One having 50 elements(users) and other with 20000 elements(allUsers). I have to filter users based on if they are present in allUsers.

For that, i am converting allUsers into object and using that object to filter out users.

allUsers is an array of object with 3 keys.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, creating object from array is taking too much of time. How can i reduce the time of the overall operationn?

  const usersMap = allUsers.reduce((aa, user) => {
    acc = { ...aa, [user.id]: user }
    return aa
  }, {})

  const matchedUsers = users.reduce((aa, user) => {
    const mappedUser = usersMap[user.id]
    if (mappedUser) {
      aa.push(mappedUser)
    }
    return aa
  }, [])

>Solution :

Your use of spread is definitlely going to slow this down. { ...aa, [user.id]: user } creates a new object every iteration rather than just adding a new property to it, and in so doing has to iterate every property of the spread object again making your reduce approach O(n^2) rather than being O(n).

You can start by making your reduce more efficient by removing the unnecessary spread and simply assigning a new property in the accumulator.

const usersMap = allUsers.reduce((aa, user) => {
    aa[user.id] = user;
    return aa;
}, {});

Or you can try using a Map

const usersMap = new Map(allUsers.map((user) => [user.id, user]));

const matchedUsers = users.reduce((aa, user) => {
  if (usersMap.has(user.id)) {
    aa.push(usersMap.get(user.id));
  }
  return aa;
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading