Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array by number?

Tags:

arrays

ruby

I've got an array with a list of numbers, e.g.

[10, 30, 50, 54, 56, 95, 97, 99] 

If I provide a number e.g. 52, it needs to return the next lowest number in the array, in this case that would be 50.

What's the cleanest way to do this?

Please state if the array must be sorted first.

like image 250
cjm2671 Avatar asked Jun 07 '26 20:06

cjm2671


2 Answers

I'd go for something like this (no need for sorting):

[10, 30, 50, 54, 56, 95, 97, 99].select {|n| n < 52}.max
like image 199
nesiseka Avatar answered Jun 09 '26 09:06

nesiseka


I think this can work for a sorted array:

[10, 30, 50, 54, 56, 95, 97, 99].sort.reverse.find { |el| el < number }

It simply changes the sorting direction to descending and finds first smaller element

like image 35
Piotr Kruczek Avatar answered Jun 09 '26 09:06

Piotr Kruczek



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!