Search code examples
rethinkdbrethinkdb-javascript

RethinkDB: Get last N from an object


What would be an efficient way to get the last N key-value pairs from an object? Sorted by key name and N being arbitrary integer. Ideally the returned type should also be an object.


Solution

  • If you want the last n, I would write obj.coerceTo('array').slice(-n).coerceTo('object'). (Objects in RethinkDB implicitly sort their fields by the key.) If you want the first n, I'd write .slice(0, n) instead of .slice(-n).