1

I have the below array with me -

 var  arrayInt: Array[Int] = Array(400, 200, 20, 30, 50,1000)

Also the below condition. I need to fetch the first 2 occurrences from the array where it satisfies the condition arrayInt < int_max.

 var int_max = 100

Expected Output

Array( 20, 30)
2
  • 1
    In such case, first avoid using Array or var Commented Jun 15, 2020 at 6:41
  • Thanks for your comment! What should be the best practice then? Commented Jun 15, 2020 at 6:43

2 Answers 2

2

You should use filter method available for all scala collections.

val arrayInt: Array[Int] = Array(400, 200, 20, 30, 50, 1000)
val filtered = arrayInt.filter(_ < 100).take(2)
println(filtered.mkString(","))

Sign up to request clarification or add additional context in comments.

Comments

2

Filtering the array on the condition removes the too-large numbers, then taking the first two of the remaining numbers like so:

val  arrayInt: Array[Int] = Array(400, 200, 20, 30, 50,1000)
val intMax = 100

arrayInt.filter( _ < intMax ).take( 2 )

Comments

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.