0

arr = [4, 9, 0, -3, 16, 7]

Is there any simple way to find the indicies of the lowest x elements? Something like this? arr.min_index(4)

E.A.
  • 321
  • 1
  • 4
  • 13

2 Answers2

3
arr.each_index.min_by(x) { |i| arr[i] }

or

arr.each_with_index.min(x).map(&:last)

Demo:

> arr, x = [4, 9, 0, -3, 16, 7], 4
=> [[4, 9, 0, -3, 16, 7], 4]
> arr.each_index.min_by(x) { |i| arr[i] }
=> [3, 2, 0, 5]
> arr.each_with_index.min(x).map(&:last)
=> [3, 2, 0, 5]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0

Here's one simple way to do it:

class Array
  def min_index(n)
    each_with_index.sort.map(&:last).first(n)
  end
end

>> arr = [4, 9, 0, -3, 16, 7]
>> arr.min_index(4)
#> [3, 2, 0, 5]
>> [4, 2, 2].min_by(2)
#> [1, 2]
moveson
  • 5,103
  • 1
  • 15
  • 32