Search code examples
angulargoogle-cloud-firestoreangularfire

Angular Firestore: Randomize query result


If I have a code below to reference all records and sync for changes:

this.productsRef.valueChanges({ idField: 'id' });

How do I randomize the order of the documents I get but retain the synchronization of the collection and documents to Firestore?

UPDATED: I played around a bit, this seems to work:

import { shuffle } from "lodash";
...    
this.productsRef.valueChanges({ idField: 'id' }).subscribe((res:Product[])=> {
   this.products = shuffle(res);
});

Solution

  • Converting my comment into answer

    The workaround you have found seems good, but you can add uniq() in the third line i.e.,

    this.products = uniq(shuffle(res)); 
    

    so that documents will appear only once. As mentioned in the Documentation 1

    The _.uniq method is used to create an array of unique values in order, from all given arrays using SameValueZero for equality comparisons.

    And as per the Documentation 2, the shuffle() method

    The _.shuffle() method creates an array of shuffled values from the given collection using a version of the Fisher-Yates shuffle algorithm.