Jack Franklin
Jack Franklin

Reputation: 3765

Filtering empty arrays from array of arrays in Scala

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

Answers (4)

oblivion
oblivion

Reputation: 6548

In your case, you could use:

array.filterNot(_.corresponds(Array("")){_ == _})

Upvotes: 0

tuitui
tuitui

Reputation: 1

Use the following:

val a = Array(Array(), Array(), Array(3,1,2016), Array(1,2,3026))

a.filter(_.length>0)

Upvotes: -1

Stefan Endrullis
Stefan Endrullis

Reputation: 4208

Edit (with Rogach's simplification):

array.filterNot(_.forall(_.isEmpty))

Upvotes: 16

Luigi Plinge
Luigi Plinge

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

Related Questions