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 and Firestore – Filter and Reducer at the same time

I have two arrays of object that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I’m trying this:

function loadAllUsersDontFollow() {
  
firestore()
        .collection("users")
        .where("id", "!=", user?.id)
        .get()
        .then((response) => {
          const data = following.filter((follow) => {
            return response.docs.reduce(function (res, item, index) {
              if (item.data().id !== follow.userId) {
                res.push(item);
              }
              return res;
            }, []);
          });
        });
}

the return of the function is being totally contrary to what I need, it is returning the users that I already follow, but I need the users that I still don’t follow. Help-me, please.

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

>Solution :

This would be easier if you created a hashed set of follower IDs…

const followerIds = new Set(following.map(({ userId }) => userId));

that you can then use to filter users…

const data = response.docs.filter((doc) => !followerIds.has(doc.data().id));

Your issue is that filter() expects a Boolean value returned from the callback. You were returning an array which, even if empty, is always truthy.

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