0

Having the following array, it defines the sorting :

[300, 450, 345, 23]

And the following array, unsorted :

[
  {id: 450, title: 'rand1'},
  {id: 23, title: 'rand3'},
  {id: 300, title: 'rand0'},
  {id: 345, title: 'rand2'},
]

I'd like the first array to be a "rule" to sort my second array (probably by matching the id key).

How can i get achieve this cleanly ?

1 Answer 1

5

Naïve approach:

sorter = [300, 450, 345, 23]
input = [
   {id: 450, title: 'rand1'},  
   {id: 23, title: 'rand3'},  
   {id: 300, title: 'rand0'},  
   {id: 345, title: 'rand2'},  
]  
input.sort do |h1, h2|
  sorter.index(h1[:id]) <=> sorter.index(h2[:id])
end
#⇒ [
#     {:id=>300, :title=>"rand0"},
#     {:id=>450, :title=>"rand1"},
#     {:id=>345, :title=>"rand2"},
#     {:id=>23, :title=>"rand3"}]

or even simper:

input.sort_by { |h| sorter.index(h[:id]) }
Sign up to request clarification or add additional context in comments.

1 Comment

in case you know this one @mudasowba stackoverflow.com/questions/49150665/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.