Ruby reorder an array based on the contents of a subset array -
i have array ordered hash[:points]
original = [{a: "bill", points: 4}, {b: "will", points: 3}, {c: "gill", points: 2}, {d: "pill", points: 1}]
i want change order of it's elements based on order of subset array, ordered hash[:points]
.
subset = [{c: "gill", points: 2}, {b: "will", points: 1}]
the subset's elements contained in original. subset's length , order come @ random. may have two, three, or 4 elements, in order.
i want incorporate order of subset original array. can done reordering original, or recreating original in correct order. either do. don't want merge them. keys
, values
in subset not important, order of elements.
for example, above subset should produce this.
# bill , pill retain original position # gill , swap places per ordering of subset [{a: "bill", points: 4}, {c: "gill", points: 2}, {b: "will", points: 3}, {d: "{pill}", points: 1}]
another example subset: [{c: "gill", points: 3}, {b: "will", points: 2}, {a: "bill", points: 1}]
# pill remains @ index 3 since not in subset # gill, will, , bill reordered based on order of subset [{c: "gill", points: 3}, {b: "will", points: 2}, {a: "bill", points: 1}, {d: "pill", points: 1}]
i've tried bunch of stuff past couple of hours, i'm finding harder looks.
my solution has 2 steps:
- collect relevant elements original array, , sort them according subset order.
- replace them in original array new order.
here code:
mapped_elements = subset.map { |i| original.find { |j| j.keys == i.keys } } result = original.map |i| if subset.find { |j| j.keys == i.keys } mapped_elements.shift else end end
for subset = [{c: "gill", points: 2}, {b: "will", points: 1}]
result be:
[{a: "bill", points: 4}, {c: "gill", points: 2}, {b: "will", points: 3}, {d: "{pill}", points: 1}]
for subset = [{c: "gill", points: 3}, {b: "will", points: 2}, {a: "bill", points: 1}]
result be:
[{c: "gill", points: 3}, {b: "will", points: 2}, {a: "bill", points: 4}, {d: "pill", points: 1}]
Comments
Post a Comment