Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a TCL array based on the values of its keys?

The INITIAL_ARRAY is

Key -> Value
B      8
C     10
A      5
E      3
D      1

To get a sorted array based on key, I use

set sorted_keys_array [lsort [array names INITIAL_ARRAY]]

to get the output

Key -> Value
A     5
B     8
C     10
D     1
E     3

Like wise, how to get a sorted tcl array based on values of keys, like output below?

Key -> Value
 C     10
 B     8 
 A     5
 E     3
 D     1
like image 281
user1228191 Avatar asked Dec 16 '22 14:12

user1228191


1 Answers

Starting with Tcl 8.6, you could do

lsort -stride 2 -integer [array get a]

which would produce a flat list of key/value pairs sorted on values.

Before lsort gained the -stride option, you had to resort to constructing a list of lists out of the flat list array get returns and then sort it using the -index option for lsort:

set x [list]
foreach {k v} [array get a] {
    lappend x [list $k $v]
}
lsort -integer -index 1 $x
like image 135
kostix Avatar answered Mar 24 '23 21:03

kostix