6

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.

2
  • 5
    But they are not empty; they contain a String Commented Jul 17, 2012 at 13:46
  • Apologies, that's my poor phrasing of it. I'll amend my question to clarify. Commented Jul 17, 2012 at 13:46

4 Answers 4

16

Edit (with Rogach's simplification):

array.filterNot(_.forall(_.isEmpty))
Sign up to request clarification or add additional context in comments.

2 Comments

I believe that x.isEmpty is not needed here - if x is indeed empty, x.forall(_.isEmpty) would still return true.
Thanks for the hint, Rogach. You're absolutely right. I incorporated your suggestion in the answer.
0

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.

Comments

0

In your case, you could use:

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

Comments

-1

Use the following:

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

a.filter(_.length>0)

3 Comments

Please format your code accroding to this site’s guidelines (either including it in backquotes or indenting it of an appropriate number of spaces) so that it appears in a monospaced font on a grey background. Also, try to apply your solution to the given input and show that it produces the desired output. Welcome to this site!
thanks a lot,it‘s my first time to commit the answer,i will be better next time;
@tuitui You can edit your answer via the small "edit" text below it. I will do this for the moment, however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.