I have questions$
observable which returns more than 10
question objects from Firestore
.
this.questions$ = this.moduleCollection$.doc(module.id)
.collection('questions').valueChanges();
Now i want to limit the result with 10
questions randomly.
I can limit the query like this
this.questions$ = this.moduleCollection$.doc(module.id)
.collection('questions',ref => ref.limit(10)).valueChanges();
But i don't know how to get it randomly, is there any Rxjs
operators do so?
What i have tried (Extending @Richard Matsen's answer)
const sampleSize = 2
const randomIndex = (array) => Math.floor(Math.random() * array.length)
const addIndexes = (array) => array.map((item, index) => {
item['id'] = index
return item
})
const removeIndexes = (array) => array.map(item => {
delete item.id
return item
})
this.questions$ =
this.moduleCollection$.doc(module.id).collection('questions').valueChanges()
.map(addIndexes)
.map(r => r[randomIndex(r)])
.repeat()
.scan((a, c) => a.map(a => a.id).indexOf(c.id) === -1 ? a.concat(c) : a, [])
.skipWhile(array => array.length < sampleSize)
.take(1)
.map(array => array.sort((a, b) => a.id - b.id))
.map(removeIndexes)