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.

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;
}, []);

Leave a Reply