Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element at given index

In Scala, I have an Array[Int] object called elem.

I would like to remove the element at index k.

I have tried this:

elem.filter(! _.equals(elem(k)))

However, this removes all elements which are equal to elem(k).

How could I remove only the element at the index k?

like image 358
octavian Avatar asked Feb 15 '16 19:02

octavian


People also ask

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

ArrayList. remove(int index) method removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

How do I remove a specific element 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.

How do I remove a specific item from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.


1 Answers

For all collections (you can view Array as such) you can use the immutable patch method that returns a new collection:

val xs = Seq(6, 5, 4, 3)
// replace one element at index 2 by an empty seq:
xs.patch(2, Nil, 1)  // List(6, 5, 3)

If you want a mutable collection, you might want to look at Buffer instead of Array.

val ys = collection.mutable.Buffer(6, 5, 4, 3)
ys.remove(2)
ys // ArrayBuffer(6, 5, 3)
like image 64
0__ Avatar answered Oct 13 '22 10:10

0__