Reordering an array in the same order as another array was reordered
-
30-10-2019 - |
Question
I have two arrays a
, b
of the same length:
a = [a_1, a_2, ..., a_n]
b = [b_1, b_2, ..., b_n]
When I sort a
using sort_by!
, the elements of a
will be arranged in different order:
a.sort_by!{|a_i| some_condition(a_i)}
How can I reorder b
in the same order/rearrangement as the reordering of a
? For example, if a
after sort_by!
is
[a_3, a_6, a_1, ..., a_i_n]
then I want
[b_3, b_6, b_1, ..., b_i_n]
Edit
I need to do it in place (i.e., retain the object_id of a
, b
). The two answers given so far is useful in that, given the sorted arrays:
a_sorted
b_sorted
I can do
a.replace(a_sorted)
b.replace(b_sorted)
but if possible, I want to do it directly. If not, I will accept one of the answers already given.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow