Sort Inlinks in DataviewJS

I’m using DataviewJS to create a footer for my journals, and one piece of it is to show the inlinks:
const linksIn = dv.current().file.inlinks
It’s working, but they are not sorted. I’ve tried a number of things, including:
.sort( (a, b) => a.inlinks.localeCompare(b.inlinks))
and:
.sort((p) => p.inlinks, "asc")
based on other ‘stuff’ I’d sorted, but neither work. Anyone know how to tell my inlinks to sort in DataviewJS?

As far as I know, You can’t use sort((a,b) => ...) notation with proxy array returned by dvjs functions.

You could write it like this:

const parseNameFromPath = (path) => {
  const slashPos = path.lastIndexOf("/")
  return path.slice(slashPos > 0 ? slashPos : 0)
}

const sortedLinksIn = [...dv.current().file.inlinks].sort( (a, b) => parseNameFromPath(a.path).localeCompare(parseNameFromPath(b.path)))

dv.list(sortedLinksIn)
  1. I’m converting the dv proxy array into a plain js array
  2. Then I’m comparing only the name of the files using parseNameFromPath function since a.path also contains the folder

PS. If you want to call dv proxy functions on the array after the sort occurred, you should convert it back using dv.array(sortedLinksIn)

Complicated stuff, but it works! Thanks @Krakor!

The thing is that your attempts try to sort directly on the links, which is a complex object, and that’s not eligible for sorting straight out of the box. The path variable of the link however, can be used for sorting, so if you had tried something like .sort( l => l.path ) you could have come close, but it would still sort on the folder before the actual file names.

A further refinement of this, could be to do something like the following query:

```dataviewjs
const inlinks =  dv.current()
  .file.inlinks
  .sort( l => l.path.split("/").pop() )

dv.list(inlinks)
```

Here we explicit pick out the part which we want to sort on, and the explanation on how to get this part is:

  • l.path – pick the path part of the link, as that holds the file name
  • .split("/")– Split the path according to the folders and filename parts, as separated by the forward slash, /
  • pop() – Extract only the last part, aka the filename (actually including the .md part, but that shouldn’t matter for most sorting)

Wow @holroy , even slicker code, and it works! One issue, I’d prefer to have it descending. I hoped that adding a ‘-’ before l.path.split("/").pop() would work, but didn’t. Also tried adding .reverse() to the end of the sort line, but no luck. Is changing to descending going to make this code more complex?

Change the end to be .pop(), "desc" ), but keep the start of the line.

As usual, you rock @holroy , works like a charm. Thanks!

1 Like

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