0

I have two arrays like this: arr1 = [name1, name2,name3] and arr2 = [[name1,10], [name3,15], [name2, 20]]. Now I want to sort the arr2 based on the order of arr1. The order of arr2 will change whenever order of arr1 change. I try this:

hash_object = arr2.each_with_object({}) do |obj, hash| 
  hash[obj.name] = obj
end

arr1.map { |index| hash_object[index] }

But the result returned [nil, nil, nil]. I confused of this is the right way, and I only made mistake or are there another ways to solve my problem. Can someone help me?

1
  • If future, consider waiting longer before making a selection. There's no rush, and a quick selection can discourage other answers. Commented May 26, 2015 at 4:06

3 Answers 3

6

I would do something like this:

arr2.sort_by { |element| arr1.index(element.first) }
Sign up to request clarification or add additional context in comments.

2 Comments

Did you mean sort_by? I expected this to raise an exception (since sort takes two arguments), but it returned, [["name2", 20], ["name3", 15], ["name1", 10]], which is not correct, of course.
@CarySwoveland: You are right - especially because sort_by is usually faster than sort.
1
arr1 = ["name1", "name2", "name3"]
=> ["name1", "name2", "name3"]
arr2 = [["name1",10], ["name3",15], ["name2", 20]]
=> [["name1", 10], ["name3", 15], ["name2", 20]]
arr2.sort_by { |e| arr1.index(e[0]) }
=> [["name1", 10], ["name2", 20], ["name3", 15]]

Comments

0

Here's another way:

arr2.values_at(*arr2.map { |str,_| arr1.index(str) })
  #=> [["name1", 10], ["name2", 20], ["name3", 15]] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.