Filtering empty arrays from an array of arrays in Scala

I have an array of arrays of type String that looks something like this:

 [[""],["lorem ipsum", "foo", "bar"], [""], ["foo"]] 

What I would like to do is filter out all the elements of the array, which themselves are an empty array (where in this case the "empty array" I mean arrays containing only an empty string), to leave me with:

 [["lorem ipsum", "foo", "bar"], ["foo"]] 

However, I'm struggling to find a way to do this (still new to Scala) - any help is much appreciated!

Thanks.

+6
source share
4 answers

Edit (using simplification of Stagger):

 array.filterNot(_.forall(_.isEmpty)) 
+16
source

In your description, you ask how

filter out all elements of the array that contain only an empty string.

The currently accepted answer does this, but also filters out empty arrays and arrays containing several empty strings (i.e. not only [""] , but also [] and ["", "", ""] , etc. d.). (In fact, the first part x.isEmpty || completely redundant.) If you translate your requirement literally, if your array is xss , you need

 xss.filter(_ != Array("")) // does not work! 

This does not work, because the equals method for Java arrays does not work, as you might expect . Instead, when comparing arrays, use the sameElements or deep :

 xss.filterNot(_ sameElements Seq("")) xss.filter(_.deep != Seq("")) 

In idomatic Scala code, you do not use Array much, so this does not happen too often. Prefer Vector or List .

0
source

In your case, you can use:

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

Use the following:

 val a = Array(Array(), Array(), Array(3,1,2016), Array(1,2,3026)) a.filter(_.length>0) 
-1
source

Source: https://habr.com/ru/post/920683/


All Articles