Collection.sortBy()

Same as toArray() but with manual sorting applied to the array. Similar to Table.orderBy() but does sorting on the resulting array rather than letting the backend implementation do the sorting.

Syntax

collection.sortBy(keyPath, callback)

Parameters

keyPath: StringName of a property or sub property to use for sorting.
callback: Functionfunction (array) { }optional

Callback Parameters

array: ArrayArray containing the found objects

Return Value

Promise

Remarks

Items in a Collection is naturally sorted by the index or primary key that was used in the where() clause. However, if you need sorting on another property than the index, you can use this method to do so. Also, if Collection.or() has been used, the Collection is no longer sorted unless you use this method.

If callback is omitted and operation succeeds, returned Promise will resolve with the result of the operation, calling any Promise.then() callback.

If callback is specified and operation succeeds, given callback will be called and the returned Promise will resolve with the return value of given callback.

If operation fails, returned promise will reject, calling any Promise.catch() callback.

To sort in descending order, use Collection.reverse() on the collection before calling sortBy().

// Query by age but sort by name in descending order:
db.friends
  .where('age')
  .above(25)
  .reverse() 
  .sortBy('name');

See Also

Table.orderBy()

Table of Contents