From: Robert Klemme Date: 2013-06-18T02:57:01+09:00 Subject: Re: Compare and sort one array according to another. --001a11c3d73cc442c204df5d52b4 Content-Type: text/plain; charset=ISO-8859-1 On Mon, Jun 17, 2013 at 5:43 PM, masta Blasta wrote: > I have two arrays of objects that look something like this: > > arr1 = [ > Obj1(prop1, prop2, id), > Obj2(prop1, prop2, id), > Obj3(prop1, prop2, id) > ] > > arr2 = [ > OthrObj1(prop1, prop2, ref_id), > OthrObj2(prop1, prop2, ref_id), > OthrObj3(prop1, prop2, ref_id) > ] > > The objects in arr1 are ordered by id (just as an example). The > objects in arr2 have a 1-1 relationship with the objects in arr1, > however they are not sorted. They need to be sorted to match the order > of the objects in arr1. The order of arr1 is not predictable so arr2 has > to be compared to arr1 to find the order. The two arrays are always the > same size. No items should repeat, however this might be something i > need to guard against. For now let's assume no items repeat. > > My current solution is to make a temp array and then build it with the > items in order. It's ok but i'm wondering if there's a better ruby > method. > Something like this? arr2.sort_by {|o| arr1.find_index {|a| o.prop1 == a.prop1 && o.prop2 == a.prop2}} Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --001a11c3d73cc442c204df5d52b4 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable



On Mon, Jun 17, 2013 at 5:43 PM, masta Blasta <= ;lists@ruby-forum= .com> wrote:
I have two arrays of objects that look somet= hing like this:

arr1 =3D [
Obj1(prop1, prop2, id),
Obj2(prop1, prop2, id),
Obj3(prop1, prop2, id)
]

arr2 =3D [
OthrObj1(prop1, prop2, ref_id),
OthrObj2(prop1, prop2, ref_id),
OthrObj3(prop1, prop2, ref_id)
]

The objects in arr1 are ordered by id (just as an example). The
objects in arr2 have a 1-1 relationship with the objects in arr1,
however they are not sorted. They need to be sorted to match the order
of the objects in arr1. The order of arr1 is not predictable so arr2 has to be compared to arr1 to find the order. The two arrays are always the
same size. No items should repeat, however this might be something i
need to guard against. For now let's assume no items repeat.

My current solution is to make a temp array and then build it with the
items in order. It's ok but i'm wondering if there's a better r= uby
method.
=A0
=A0
Something like this?

arr2.sort_by {|o| arr1.find_index {|a| o.prop1= =3D=3D a.prop1 && o.prop2 =3D=3D a.prop2}}

Kind regards

robert


--
remember.guy do |as, often|= as.you_can - without end
http://blog.rubybestpractice= s.com/
--001a11c3d73cc442c204df5d52b4--