DataViewJS - sorting not working as expected

I try to create a list with all my files sorted by number of lines descending. For this I found the following snippet:

```dataviewjs
//get all md files in vault
const files = app.vault.getMarkdownFiles()

//create an array with the filename and lines that include the desired tag
let arr = files.map(async(file) => {
  const content = await app.vault.cachedRead(file)
//turn all the content into an array
let lines = await content.split("\n").filter(line => line.includes("- [?]"))
return ["[["+file.name.split(".")[0]+"]]", lines]
})

//resolve the promises and build the table
Promise.all(arr).then(values => {
console.log(values)
//filter out files without "ad-question" and the note with the dataview script
const exists = values.filter(value => value[1][0] && value[0] != "[[dataviewjs-testing]]")
dv.table(["file", "lines"], exists)
})

Sorting is not included in there as it doesn’t work with the array built there. I tried out a very simple example with an array of objects which isn’t sorted as well:

	let foo = [{a: "b", c: "d", e: 10}, {a: "bb", c: "dd", e: 5}, {a: "bb", c: "dd", e: 15}]
	dv.table(["File", "Rating"], 
		foo
	    .sort(b => [b.e])
	    .map(b => [b.a, b.e])
	)

I would expect in the latter example that it’s sorted by the number, but it isn’t. What am I missing here?

You want:

foo.sort((a, b) => a.e - b.e)

My favourite resource for JS functions is here: Array.prototype.sort() - JavaScript | MDN

2 Likes

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