bsky
bsky

Reputation: 20222

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?

Upvotes: 5

Views: 7020

Answers (4)

elm
elm

Reputation: 20405

Using splitAt as follows,

val (l,r) = xs.splitAt(k)
l ++ r.drop(1)

Also in a similar way to using zipWithIndex, we generate the range of indices and filter out that with value k, we can then extract the rest, like this,

(0 until xs.size).filter(_ != k).map(xs)

Using collect,

 (0 until xs.size).collect {
   case x if x != k => xs(x)
 }

Using a for comprehension,

for (i <- 0 until xs.size if i != k) yield xs(i)

A more general form where we have a set of indices to exclude, namely for

val exclude = Set(k,k+3)
for (i <- 0 until xs.size if !exclude(i)) yield xs(i)

we map indices not in exclude.

Upvotes: 2

hasumedic
hasumedic

Reputation: 2167

A complementary way of achieving this would be by taking and dropping around the index:

val filteredElem = elem.take(k) ++ elem.drop(k+1)

Upvotes: 3

0__
0__

Reputation: 67280

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)

Upvotes: 18

Crembo
Crembo

Reputation: 5438

elem.zipWithIndex.filter(_._1 != k).map(_._2)

If you have Array("a", "b", "c") then zipWithIndex - converts into Array((0, "a"), (1, "b"), (2, "c"))

Upvotes: 3

Related Questions