Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array by range of numbers

I have an array with a bunch of numbers:

let array = [0,10,24,3,4,5,67,7,8,9,2,1,34,6,7,2,4,6,8,0,303,444]

How do I get all the values between 5 and 10 for example? There has to be a better way then a for iteration through all the numbers or?


1 Answers

Use filter for this with different alternatives:

1: let filtered = array.filter({ $0 >= 5 && $0 <= 10 })

2: let filtered = array.filter({ 5..<11 ~= $0 })

3: let filtered = array.filter((5...10).contains)

All will get you [10, 5, 7, 8, 9, 6, 7, 6, 8]

like image 172
Rashwan L Avatar answered Jun 04 '26 13:06

Rashwan L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!