Skip to content

Sorting a collection - year and month #286

Open
@practicalli-johnny

Description

@practicalli-johnny

I have the following structure {[2019 10] 21, [2020 9] 17} where format of each item is "[year month] amount". How best to sort this structure such that I have the latest "month" last? Data is sorted first by year and then by month

Data generated by

   (->> data (map #(assoc % :grouping [(:year %) (:month %)]))
        (group-by :grouping)
        (map (fn [[g t]]
               [g (->> t (map :amount) (reduce +))]))
        (into {})))

(group-by (juxt :year :month)) is shorter
e.g. no need for the first map

use (into (sorted-map)) instead of (into {}) to sort by keys

 (->> data 
             (group-by (juxt :year :month)) 
             (map (juxt key #(->> % val (map :amount) (reduce +)))) 
             (into (sorted-map)))
 {[2019 10] 21, [2020 9] 17}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions