Forum OpenACS Q&A: Sorting list of arrays by value

Request notifications

Posted by Jade Rubick on
This is a problem I've commonly come across, and I was wondering if any of you Tcl wizards had the solution for.

I am setting up a list of ingredients to be displayed.

set list_of_ingredients [list] 

db_foreach example "select id, name, percentage from recipe" {
  lappend list_of_ingredients $id
  set ingredient_name($id) $name
  set ingredient_percentage($id)  $percentage

[other stuff]

foreach one_ingredient_id $list_of_ingredients {
  append page_body " <li> 
How would I sort the list of ingredients by percentage? Granted, I could sort the database call (by adding ORDER BY percentage), but I actually do some manipulation of the percentages later on, so this doesn't work for me.

Am I going about this the wrong way? Or is there something I'm missing out on here?

Posted by Tilmann Singer on
Check out lsort -index, to sort a list of lists depending on a specific value in the inner list. You need to somehow construct a list like this {{id percentage} {id percentage}}, which unfortunately array get won't give you, but there are numerous other ways to do that.
Posted by Jade Rubick on
Exactly what I was looking for. I knew there had to be an easier way. For reference, this command is located at: lsort.htm#M12

It's not on Philip's Tcl Book.