Reputation: 3765
I have an array of arrays of type String
, which looks something like:
[[""],["lorem ipsum", "foo", "bar"], [""], ["foo"]]
What I'd like to do is filter out all of the elements in the array that are themselves an empty array (where in this instance, by "empty array", I mean arrays that contain just an empty string), to leave me just with:
[["lorem ipsum", "foo", "bar"], ["foo"]]
However I'm struggling to find a way to do this (still new to Scala) - any help much appreciated!
Thanks.
Upvotes: 6
Views: 9498
Reputation: 6548
In your case, you could use:
array.filterNot(_.corresponds(Array("")){_ == _})
Upvotes: 0
Reputation: 1
Use the following:
val a = Array(Array(), Array(), Array(3,1,2016), Array(1,2,3026))
a.filter(_.length>0)
Upvotes: -1
Reputation: 4208
Edit (with Rogach's simplification):
array.filterNot(_.forall(_.isEmpty))
Upvotes: 16
Reputation: 51109
In your description you ask how to
filter out all of the elements in the array that ... contain just an empty string.
The currently accepted answer does this, but also filters out empty arrays, and arrays containing multiple empty strings (i.e. not just [""]
, but []
and ["", "", ""]
etc. as well. (In fact, the first part x.isEmpty ||
is completely redundant.) Translating your requirement literally, if your array is xss
, you need
xss.filter(_ != Array("")) // does not work!
This doesn't work because the equals
method for Java arrays doesn't work as you might expect. Instead, when comparing Arrays, use either sameElements
or deep
:
xss.filterNot(_ sameElements Seq(""))
xss.filter(_.deep != Seq(""))
In idomatic Scala code you don't use Array
much, so this doesn't crop up too often. Prefer Vector
or List
.
Upvotes: 0