Use dataview to select a random note from a specified folder

What I’m trying to do

I’m trying to create a Dataview query that lists 5 random notes from within a specific folder, updating whenever I switch back and forth through notes

Things I have tried

So, so, so many different codes, tutorials YouTube videos, and third-party plugins; I just can’t seem to make it work!

So far, this code is almost perfect

FROM "01 Questline/Side Quests"
SORT file.mtime DESC
FLATTEN date(now) as Now
FLATTEN (file.mtime.year + file.mtime.hour + + 
	     file.mtime.hour + file.mtime.minute + file.mtime.second + 
	     file.size + Now.hour + Now.minute + Now.second) * 15485863 
	     as Hash
FLATTEN ((Hash * Hash * Hash) % 2038074743) / 2038074743 as Rand

But it relies on me editing the notes frequently to update the modification time, otherwise it just provides the same 5 most recently edited notes in a different order.

Is there any way to randomize the results without relying on other variables?

1 Like

Sounds like you need DataviewJS! You could try something like this:

let docs = dv.pages('"FolderName"');
let length = docs.length;
let numberToReturn = 5;
var randos = getRandos(docs, length, numberToReturn);


function getRandos(list, max, itemNum) {
  var items = [];
  for (var i=0;i<itemNum;i++) {
    items.push(list[Math.floor(Math.random() * max)];
  return items;

You’ll have to replace “FolderName” with the path to your folder of choice.

This code generates five random numbers using Math.random, and it should give you new notes every time you open the document. I tested in my own vault and it seems to work (although duplicates are possible)

(Also you’ll have to turn DataviewJS on in your settings)

1 Like

Absolutely perfect! Thank you so much!

1 Like

@webinspect, is there a way to refine this further to choose a random heading from within a note? I’m trying to streamline a little, and figured if this could be boiled down to choosing from multiple headings in a singular note, instead of having a million different notes it would save heaps of space!

(Thank you again for your previous code, it works like a charm!)

In terms of conplexity it would be a whole lot harder, and not as streamlined as the current solution or variation thereof. So I’m not sure it would be a major gain overall to switch to random headings, in fact unless you limit to just one file (or folder) the header variant would create a whole lot more file operations to achieve something similar.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.