Filter an array by number?

I have an array with a list of numbers, for example.

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

      

If I provide a number for example. 52, it needs to return the next lowest number in the array, in which case it would be 50.

What's the cleanest way to do this?

Indicate whether to sort the array first.

+3


source to share


6 answers


I would choose something like this (no sorting needed):



[10, 30, 50, 54, 56, 95, 97, 99].select {|n| n < 52}.max

      

+9


source


I think this might work for a sorted array:

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

      



It just changes the sort direction to descending and finds the first smallest element

+2


source


Another way to do it with a sorted array is to use Array#bsearch

on your reverse:

[10, 30, 50, 54, 56, 95, 97, 99].reverse.bsearch { |n| n < 52 } # => 50

      

+1


source


Use the select option instead of select because choose to iterate over all of your elements. detect returns the first occurrence that matches.

The array does not need to be sorted.

[10, 30, 50, 54, 56, 95, 97, 99].sort { |a, b| b <=> a }.detect { |v| v <= 52 }

      

+1


source


Let's assume the array is sorted:

ary = [...]
pivot = 52
ary.partition{|n| n < pivot}[0][-1]

      

0


source


You should try rindex

ary.sort.rindex {|el| el < number}

      

and that return the first matching item.

0


source







All Articles