# Sorting arrays within an array by the first object in

**URL:** <https://www.ruby-forum.com/t/sorting-arrays-within-an-array-by-the-first-object-in/106717>\
**Category:** Ruby\
**Created:** [June 13, 2007, 3:39pm UTC](https://www.ruby-forum.com/t/sorting-arrays-within-an-array-by-the-first-object-in/106717 "2007-06-13T15:39:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![miked](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ed655f/32.png) [@miked](https://www.ruby-forum.com/u/miked)\
**Post date:** [June 13, 2007, 3:39pm UTC](https://www.ruby-forum.com/t/sorting-arrays-within-an-array-by-the-first-object-in/106717/1 "2007-06-13T15:39:49Z")

</div>

Hello:

Here’s a bit of a tongue-twister:

I have a parent array of child arrays.

Each child array contains a set of objects. These objects are all from  
the same model.

I know that each child array contains at least one object. I want to  
sort on a field in the first object in each child array, and arrange the  
child arrays in the parent array according to that field in the first  
object in the child arrays. What’s the best way to do this?

I thought it was some permutation of sort\_by, but I tried a few options  
and didn’t have any luck. I wanted to take a step back and check in  
with the community to see if I could get some direction.

Thanks very much in advance.

Mike

---

<div class="post-metadata">

**Author:** ![miked](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ed655f/32.png) [@miked](https://www.ruby-forum.com/u/miked)\
**Post date:** [June 13, 2007, 3:46pm UTC](https://www.ruby-forum.com/t/sorting-arrays-within-an-array-by-the-first-object-in/106717/2 "2007-06-13T15:46:12Z")

</div>

On Jun 13, 2007, at 8:39 AM, Mike D. wrote:

> object in the child arrays. What’s the best way to do this?  
> parent\_array.sort\_by { |child\_array|  
> child\_array.first.field\_name\_here }

If I understood the question correctly.

James Edward G. II

---

<div class="post-metadata">

**Author:** ![miked](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ed655f/32.png) [@miked](https://www.ruby-forum.com/u/miked)\
**Post date:** [June 14, 2007, 4:34pm UTC](https://www.ruby-forum.com/t/sorting-arrays-within-an-array-by-the-first-object-in/106717/3 "2007-06-14T16:34:50Z")

</div>

On Jun 13, 2007, at 8:45 AM, James Edward G. II wrote:

> > arrange the  
> > child arrays in the parent array according to that field in the first  
> > object in the child arrays. What’s the best way to do this?
> 
> parent\_array.sort\_by { |child\_array|  
> child\_array.first.field\_name\_here }
> 
> If I understood the question correctly.
> 
> James Edward G. II

You have to wonder though… If you need the parent sorted, do you  
also need the child arrays each sorted? Or do you want them as they  
come in?
