2017-11-18

Spoon of Code #2: Remove element from a vector at given index

Example

You have a vector of items [:a :b :c :d :e :f :g] and you want to remove the element at index 3 (:d).

Solution:

(defn remove-at-index 
  [v i] 
  (vec (concat (subvec v 0 i) (subvec v (inc i))))) 
 
(remove-at-index [:a :b :c :d :e :f :g] 3) 
; [:a :b :c :e :f :g]

Explanation:

We use subvec to get two vectors - one with items from first (included), to item right before provided index i. Second vector consist of items right after the element at index i till the end of the collection. We then concatenate the two vectors. The last vec is there just to make sure we return the same data type the function got.