How can I drop the nth item in a collection? I want to do something like this:
(def coll [:apple :banana :orange])
(drop-nth 0 coll) ;=> [:banana :orange]
(drop-nth 1 coll) ;=> [:apple :orange]
(drop-nth 2 coll) ;=> [:apple :banana]
Is there a better way of doing this than what I've come up with so far?
(defn drop-nth [n coll]
(concat (take n coll) (nthrest coll (inc n))))
How about using keep-indexed
?
(defn drop-nth [n coll]
(keep-indexed #(if (not= %1 n) %2) coll))
This is a generic solution that works with every sequence. If you want to stick with vectors, you could use subvec
as described here.
How about this
(defn drop-nth [n coll]
(concat
(take n coll)
(drop (inc n) coll)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With