Search code examples
clojureclojurescript

Find previous item by key value in vector of maps


I have a vector of maps like this:

[{:id 2 :val "v1"} {:id 5 :val "v2"} {:id 10 :val "v3"}]

and now I want to find an element previous to chosen id. For example: when provided with id = 10 i want to receive:

{:id 5 :val "v2"}

and when selected id = 2 then return nil.

I'm new in clojurescript programming and cannot think of simple solution for this problem... Help please :)


Solution

  • You can use partition to pair adjacent maps and then search for a match on the second by id:

    (def ms [{:id 2 :val "v1"} {:id 5 :val "v2"} {:id 10 :val "v3"}])
    (ffirst (filter #(= 10 (:id (second %))) (partition 2 1 ms)))