0

Context

  • I've just queried all offers a specific user is eligible for, and have stored those objects in an array.
  • I'm now looking to sort them by priority (pri) so that I can place the first three on the user's dashboard
  • The sorting isn't happening, and I'm struggling to figure out why.

Code

    var offers = new Object;

    var offers = snap.data().offers;

    var offerpriority = new Array;

    offers.forEach(offer => {

        db.collection("offers").doc(offer).get().then(snap => {

            var thisoffer = {title: snap.data().title, pri: snap.data().priority};
            offerpriority.push(thisoffer);

        });

    });

    function compare(a, b){
        return b.pri-a.pri;
    };


    console.log(offerpriority.sort(compare));

1 Answer 1

1

You should use the orderBy() method in order to sort items in Firestore.

You should use something like :

db.collection("offers").orderBy("pri");

Moreover, if you want to limit the results, like displaying 3 of them you can use the limit() method:

db.collection("offers").orderBy("pri").limit(3);

Here you can find a more detailed documentation regarding this discussion.

Sign up to request clarification or add additional context in comments.

2 Comments

There's only a handful of offers that I want to get, the ones that appear in my user's offer array. Where would you think about adding that in?
Probably for this you should iterate through the array and do a comparison query for each of the array element using the where('offers', '=', arrayElement) method. This solution is not so efficient, but I cannot think of anything else for the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.