What is the most elegant way to remove an item at index i
in a given Array
? In a given List
?
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).
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.
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.
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
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
Use List.Extra.removeAt
from elm-community.
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
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