w3resource

Scala Programming: Remove a specific element from an given array

Scala Programming Array Exercise-7 with Solution

Write a Scala program to remove a specific element from an given array.

Note: The size of an Array can't be changed, so we can't directly delete elements from an array but replace them with "" / null etc

Sample Solution:

Scala Code:

object Scala_Array
{
  def main(args: Array[String]): Unit = 
 {
   val colors = Array("Red","Blue","Black","Green","White")
   println("Original Array elements:")
   // Print all the array elements
      for ( x <- colors ) {
         print(s"${x}, ")        
       }
     println("\nReplace some elements with ''/null etc.:")
      colors(0) = ""
      colors(3) = null
   println("Now the Original Array becomes:")
   // Print all the array elements
      for ( x <- colors ) {
         print(s"${x}, ")        
       }
  }
}

Sample Output:

Original Array elements:
Red, Blue, Black, Green, White, 
Replace some elements with ''/null etc.:
Now the Original Array becomes:
, Blue, Black, null, White,

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to check whether the value of the fast or last element of two given array ( length 1 or more) of integers are same or not.
Next: Write a Scala program to rotate one element left of an given array (length 1 or more) of integers.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/array/scala-array-exercise-7.php