How do I filter elements from a sequence based on indexes

后端 未结 8 1909
慢半拍i
慢半拍i 2021-02-19 10:08

I have a sequence s and a list of indexes into this sequence indexes. How do I retain only the items given via the indexes?

Simple example:

8条回答
  •  天涯浪人
    2021-02-19 10:44

    I know this is not what was asked, but after reading these answers, I realized in my own personal use case, what I actually wanted was basically filtering by a mask.

    So here was my take. Hopefully this will help someone else.

    (defn filter-by-mask [coll mask]
      (filter some? (map #(if %1 %2) mask coll)))
    
    (defn make-errors-mask [coll]
      (map #(nil? (:error %)) coll))
    

    Usage

    (let [v [{} {:error 3} {:ok 2} {:error 4 :yea 7}]
        data ["one" "two" "three" "four"]
        mask (make-errors-mask v)]
        (filter-by-mask data mask))
    
    ; ==> ("one" "three")
    

提交回复
热议问题