根据另一个数组(Ruby)的顺序对数组数组进行排序

时间:2022-08-20 15:57:42

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:

我有两个这样的数组:arr1 = [name1,name2,name3]和arr2 = [[name1,10],[name3,15],[name2,20]]。现在我想根据arr1的顺序对arr2进行排序。只要arr1的顺序发生变化,arr2的顺序就会改变。我试试这个:

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?

但结果返回[nil,nil,nil]。我很困惑这是正确的方法,我只是犯了错误或有其他方法来解决我的问题。有人能帮我吗?

3 个解决方案

#1


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]]

#2


6  

I would do something like this:

我会做这样的事情:

arr2.sort_by { |element| arr1.index(element.first) }

#3


0  

Here's another way:

这是另一种方式:

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

#1


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]]

#2


6  

I would do something like this:

我会做这样的事情:

arr2.sort_by { |element| arr1.index(element.first) }

#3


0  

Here's another way:

这是另一种方式:

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