-4

I would like to create a Javascript function that works like the MongoDb sort function, for sorting object arrays. I am having trouble finding any documentation on how the MongoDB sort function works.

Example of a mongodb query and sort:

documentService.findAll().sort ({name: 1, height: -1})

1 Answers1

3

Referencing my answer to Sort array of objects by string property value, a fairly compact implementation could look something like this:

const sortBy = fn => (a, b) => -(fn(a) < fn(b)) || +(fn(a) > fn(b))
const sort = o => Object.entries(o)
  .map(([k, sign]) => [sortBy(({ [k]: v }) => v), sign])
  .map(([f, sign]) => (a, b) => f(a, b) * sign)
  .reduce((f, g) => (a, b) => f(a, b) || g(a, b))

const mySort = sort({ name: 1, height: -1 })
const data = [{ name: 'b', height: 5 }, { name: 'a', height: 6 }, { name: 'a', height: 4 }, { name: 'b', height: 3 }]

console.log(data.sort(mySort))
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153