Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Sorting an array according to an element inside this array

I need to order my array according to an element of it, the reference element can vary. For example, I would like the 3 to become the first element of the array and the 1, 2 to be put at the end.

  • array = [1, 2, 3, 4, 5, 6]
  • new_array = [3, 4, 5, 6, 1, 2]

The element may vary. If I start from 5, the behavior must be the same: the elements that precede are placed at the end, so I will have :

  • new_array = [5, 6, 1, 2, 3, 4]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If I understand correctly you want to rotate the array.

array
# [1, 2, 3, 4, 5, 6]
array.rotate(2) # or array.rotate(array.index(3))
# [3, 4, 5, 6, 1, 2]

https://apidock.com/ruby/v2_5_5/Array/rotate

over 4 years ago · Santiago Trujillo Report

0

Definitely use #rotate for this in actual use, but as an alternative, you could do something like #shift and #push until the desired element is at the beginning of the array.

def rotate(arr, elem)
    arr2 = arr.clone
    arr2.push(arr2.shift) until arr2.first == elem
    arr2
end
irb(main):026:0> arr = [1, 2, 3, 4, 5, 6]
=> [1, 2, 3, 4, 5, 6]
irb(main):027:0> rotate(arr, 3)
=> [3, 4, 5, 6, 1, 2]
irb(main):028:0> arr
=> [1, 2, 3, 4, 5, 6]

Clearly, if elem is not in arr, this will run forever. You could implement some kind of check to ensure this doesn't happen, but that's just one reason you shouldn't actually do this as anything other than a learning exercise.

One approach would be to find the index of elem in arr and shift/push that many times. The &. operator may be useful in that situation to deal with the possibility of not finding elem in arr.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!