Dataviewjs code to grab files that match name and aliases

I have a footer for my journals that grabs photos, documents, etc that have text in the name that matches either the current filename, or the aliases of the current file:

const photoFiles = app.vault.getFiles()
    .filter(file => file.path.startsWith(photopath) && 
    (file.name.includes(filename) ||
    file.name.includes(aliases[0]) || 
    file.name.includes(aliases[1]) || 
    file.name.includes(aliases[2]))
    )

To match the aliases, you can see I have it hard-coded to check the first three in the array. This works, but if a note has four aliases, it won’t check the forth. How would I change this so it looks at ALL the array elements (it varies from 0 to unknown) instead of just the first three?

Assuming your query is correct in other aspects, couldn’t you just switch it around and do:

const photoFiles = app.vault.getFiles()
    .filter(file => file.path.startsWith(photopath) && 
    ( file.name.includes(filename) || aliases.includes(file.name) )
    )

No, guess I should have provided a little more context. An example filename would start with a date string, followed by a string (eg. “20240214 - Dave.jpg”). So on a file named “David.md” with an alias of “Dave” I’d want the link to “20240214 - Dave.jpg” to show up. Flipping it around would only work if the full filename were in the alias.

My bad, I’ve gotten accustomed to people using contains() to actually match stuff, which isn’t your case at all! :smiley:

Try the following and see if that doesn’t meet your requirements:

const photoFiles = app.vault.getFiles()
    .filter(file => file.path.startsWith(photopath) && 
    ( file.name.includes(filename) ||
      aliases.some( alias => file.name.includes(alias) )
    )

This worked in a little test case of mine at least!

As usual, you rock! That works, much cleaner code than I had in a number of different footers, and now I don’t need to be as concerned about how many aliases I have and what order they are in. Thanks again!

1 Like

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