Split array where previous value is greater than present value

I need to split this array:

arr = [3, 4, 5, 6, 3, 4, 5, 2, 3]

where the previous element is greater than the present element. The result should be another array:

[[3, 4, 5, 6], [3, 4, 5], [2, 3]]

2 answers

  • answered 2018-11-08 07:30 Sikandar Tariq

    def spliter array
      splited_array = []
      temp = []
      last = array[0]
      array.each do |element|
        if element >= last
          temp << element
        else
          splited_array << temp
          temp = [element]
        end
        last = element
      end
      splited_array << temp
    end
    

  • answered 2018-11-08 07:55 sawa

    arr.slice_when(&:>).to_a
    # => [[3, 4, 5, 6], [3, 4, 5], [2, 3]]