Sort array by values in a separate hash
2014-06-27 09:18
309 查看
I have a hash mapping array indices to sort values, e.g.
I have a separate array with
associated line_items (tab separated) as follows:
How can I sort the array using the values of the hash as the identifier and the key as the index of for the array?
For example, I want the array above to be sorted as follows:
{0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"}
I have a separate array with
line_item_idand
associated line_items (tab separated) as follows:
["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"]
How can I sort the array using the values of the hash as the identifier and the key as the index of for the array?
For example, I want the array above to be sorted as follows:
["item_ss \t sim2\t99\n","item_hsj \t sim3\t54\n","item_skls \t sim1\t48\n"]
a = ["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"] h = {0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"} puts a.sort_by.with_index{ |v,i| h[i] }
hash = {0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"} array = ["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"] array.sort_by { |s| hash.find { |_,v| s.start_with? v }.first } # => ["item_ss \t sim2\t54\n", # "item_hsj \t sim3\t48\n", # "item_skls \t sim1\t99\n"]
相关文章推荐
- How do I sort an array of hashes by a value in the hash?
- How do I sort an array of hashes by a value in the hash?
- Convert Array to Hash while preserving Array index values in Ruby
- How to sum values in an array with different hash
- ruby sum values in array by keys
- Sort an array alphabetically in Ruby but with capitalised words at the end
- separate odd and even numbers in an array in O(n) time complexity and O(1) space complexity
- PHP Array函数: array_key_exists() array_push() array_search() array_unique() sort() array_values()
- find unique values in an array
- [Javascript ] Array methods in depth - sort
- 访问数组中的值(Accessing Values in an Array)
- Data Structure Array: Sort elements by frequency
- 三维数组按key排序 Sorting a 3-dimensional array by a key in PHP
- 2016/3/20 数组定义 数组遍历 超全局数组 数组元素设置(in_array() 、array_reverse()、count()、array_unique()、unset()、array_values、array_merge、array_push) 列表实例
- Merge array and hash in ruby if key appears in array
- How to sort a Map<Key, Value> on the values in Java?
- Python根据内嵌的数字将字符串排序(sort by numbers embedded in strings)
- 深入聊聊Array的sort方法的使用技巧.详细点评protype.js中的sortBy方法
- how to populate values in dropdownbykey in webdynpro
- Sort a dictionary by value in JavaScript