inline
inline

Reputation: 695

How would I sort a vector of structs by value?

More specifically: how would I sort a vector of structs by the value of a certain key?

For instance, if I had:

(defstruct Item :weight :value :cost
(def my-items [(struct Item 30 50 5)
               (struct Item 15 75 20)
               (struct Item 50 10 35)])

How would I sort all of the items in the vector by, let's say, value?

Upvotes: 1

Views: 145

Answers (1)

Oleksii Kachaiev
Oleksii Kachaiev

Reputation: 6234

Use sort-by

Clojure 1.4.0
user=> (defstruct Item :weight :value :cost)
#'user/Item
user=> (def my-items [(struct Item 30 50 5)
               (struct Item 15 75 20)
               (struct Item 50 10 35)])
#'user/my-items
user=> (sort-by :value my-items)
({:weight 50, :value 10, :cost 35} {:weight 30, :value 50, :cost 5} {:weight 15, :value 75, :cost 20})

Upvotes: 5

Related Questions