Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an item at a given index from Array/List in Elm?

Tags:

arrays

list

elm

What is the most elegant way to remove an item at index i in a given Array? In a given List?

like image 745
Misha Moroshko Avatar asked Oct 13 '15 10:10

Misha Moroshko


People also ask

How do I remove an element from an ArrayList at a specific index?

The remove(int index) method present in java. util. ArrayList class removes the element at the specified position in this list and shifts any subsequent elements to the left (i.e. subtracts one from their indices).

How do I remove a specific value from an index array?

Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.

How can I remove a specific item from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


4 Answers

This should be pretty efficient:

remove : Int -> Array a -> Array a
remove i a =
  let
    a1 = Array.slice 0 i a
    a2 = Array.slice (i+1) (Array.length a) a
  in
    Array.append a1 a2
like image 75
William Casarin Avatar answered Sep 21 '22 17:09

William Casarin


Best I could think of:

removeFromList i xs =
  (List.take i xs) ++ (List.drop (i+1) xs) 

removeFromArray i =
  Array.toList >> removeFromList i >> Array.fromList 
like image 40
pdamoc Avatar answered Sep 19 '22 17:09

pdamoc


Use List.Extra.removeAt from elm-community.

like image 36
Ethan B. Martin Avatar answered Sep 19 '22 17:09

Ethan B. Martin


I needed an indexedFilter function recently. This could provide you a fold based alternative

indexedFilter : (Int -> a -> Bool) -> List a -> List a
indexedFilter p xs =
    let
        tup = List.map2 (,) [ 0 .. List.length xs - 1 ] xs
    in List.foldr (\(i,x) acc -> if p i x then x :: acc else acc) [] tup
like image 33
Simon H Avatar answered Sep 18 '22 17:09

Simon H