Anoop
Anoop

Reputation: 147

How to sort a dictionary items in vim

How to use sort function in vim script to sort a dictionary?. The help documentation doesn't seems to provide clear information on how a particular element in the dictionary can be sorted.

For eg: I am getting the quickfix items by calling getqflist(). How to sort this quickfix dictionary items with respect to line numbers?

Upvotes: 0

Views: 612

Answers (1)

Doj
Doj

Reputation: 1311

Define your comparison function, save result of the getqflist() to a variable and call sort(v, f)

Example:

function! LineLessThan(leftArg, rightArg)
  if a:leftArg['line'] == a:rightArg['line']
    return 0
  elseif a:leftArg['line'] < a:rightArg['line']
    return -1
  else
    return 1
  endif
endfunction

function! KeyLessThan(leftArg, rightArg)
  if a:leftArg['key'] ==# a:rightArg['key']
    return 0
  elseif a:leftArg['key'] <# a:rightArg['key']
    return -1
  else
    return 1
  endif
endfunction

let g:a = [{'line': 3, 'key': 'd'}, {'line': 1, 'key': 'e'}, {'line': 5, 'key': 'b'}, {'line': 2, 'key': 'a'}, {'line': 4, 'key': 'c'}]
call sort(g:a, function("LineLessThan"))
echo g:a
call sort(g:a, function("KeyLessThan"))
echo g:a

Upvotes: 2

Related Questions