我有一个数组:
[[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]]
如何映射此数组以便我得到:
[[1,["Location1", "Location2", "Location3"]],[2,["Location4", "Location5", "Location6"]]]
答案 0 :(得分:2)
执行以下操作: -
array = [[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]]
array.group_by(&:first).map { |k, v_ary| [k, v_ary.map(&:last)] }
# => [[1, ["Location1", "Location2", "Location3"]], [2, ["Location4", "Location5", "Location6"]]]
array.each_with_object(Hash.new { |hsh, key| hsh[key] = [] }) { |(f,l), h| h[f] << l }.to_a
# => [[1, ["Location1", "Location2", "Location3"]], [2, ["Location4", "Location5", "Location6"]]]
答案 1 :(得分:0)
[[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]].each_with_object({}) do |element, array|
array[element[0]] ||= []
array[element[0]].push(array[element[1]])
end.to_a
答案 2 :(得分:0)
代码或多或少会成为一个创建新数组的循环步行器,所以让它成为一个函数
def reOrgArr(arr)
i = 0
j = [[]]
loop do
group = arr[i]
name = group[1]
newgroup = group[0]
j[newgroup].push(name)
i += 1
if i > arr.len break # this will cause execution to exit the loop
end
return j
end
arr = [[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]]
newArr = reOrgArr(arr)
答案 3 :(得分:0)
您可以执行以下操作(请注意,它会更改集合中的原始项目):
arr.group_by(&:shift).transform_values(&:flatten).to_a
分步说明:
arr
[[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]]
.group_by(&:shift)
按第一个元素分组,将其从每个项目中删除(对集合中的项目进行突变){1=>[["Location1"], ["Location2"], ["Location3"]], 2=>[["Location4"], ["Location5"], ["Location6"]]}
.transform_values(&:flatten)
嵌套数组{1=>["Location1", "Location2", "Location3"], 2=>["Location4", "Location5", "Location6"]}
.to_a
将哈希转换为数组[[1, ["Location1", "Location2", "Location3"]], [2, ["Location4", "Location5", "Location6"]]]