Tom
Tom

Reputation: 561

Sorting an array alphabetically by one element - possible solution is to sort by another array?

I have an array of songs that contains:

name artist album genre

The array is completely random at the moment.

Aim

I want the user to be able to view the contents separately by name, or by artist etc..

Attempt

I recall, in another language (php) I could create a new array of, for example, artists and then sort the songs array by the artists. This is good in theory but how to implement?

I created a sorted array of artists, like this:

    songs.each { |member|
               artists << member.artist
      }

artists.sort!

This works great, and outputs all the artists to the screen alphabetically when testing.

My problem is how would I sort the songs array by the artists array? I.e. the songs would be sorted by the artists

Question

Is there an easier way to sort the songs array alphabetically?

Ultimately, it would be ideal to have an name array, artist array, album array, genre array, each of which would have the same contents as the songs array, but sorted alphabetically by the relevant field.

Thanks for any help.

Example

Input:

Songs =

[['Song A','B Artist'],['Song D','A Artist'],['Song D','C Artist']]

Example Output

Artist =

[['A Artist','Song D'],['B Artist','Song A'],['C Artist','Song D']]

Upvotes: 0

Views: 87

Answers (1)

Stefan
Stefan

Reputation: 114178

There's Enumerable#sort_by:

songs = [
  {name: "Like a Rolling Stone", artist: "Bob Dylan"},
  {name: "(I Can't Get No) Satisfaction", artist: "The Rolling Stones"},
  {name: "Imagine", artist: "John Lennon" }
]

songs.sort_by { |song| song[:name] }
#=> [
#     {:name=>"(I Can't Get No) Satisfaction", :artist=>"The Rolling Stones"},
#     {:name=>"Imagine", :artist=>"John Lennon"},
#     {:name=>"Like a Rolling Stone", :artist=>"Bob Dylan"}
#   ]

songs.sort_by { |song| song[:artist] }
#=> [
#     {:name=>"Like a Rolling Stone", :artist=>"Bob Dylan"},
#     {:name=>"Imagine", :artist=>"John Lennon"},
#     {:name=>"(I Can't Get No) Satisfaction", :artist=>"The Rolling Stones"}
#   ]

Upvotes: 2

Related Questions