这是分层数据集。
data = [
{
name: "Project success",
owner_name: "Nusaiba S.",
created_at_in_sec: 1539089917,
children: [
{
name: "Develop MVP",
parent_name: "Project success",
owner_name: "Nusaiba S.",
created_at_in_sec: 1539105107,
children: [
{
name: "Requirement Analysis",
parent_name: "Develop MVP",
owner_name: "Nusaiba S.",
created_at_in_sec: 1539105117
},
{
name: "New Feature Implement",
parent_name: "Develop MVP",
owner_name: "Nusaiba S.",
created_at_in_sec: 1539105119
}
]
},
{
name: "Added Task to Jira",
parent_name: "Project success",
owner_name: "Nusaiba S.",
created_at_in_sec: 1539090003
},
{
name: "Meeting with Client",
parent_name: "Project success",
owner_name: "Jawad S.",
created_at_in_sec: 1539104779
}
]
}
]
我想按以下要求对分层数据进行排序-
答案 0 :(得分:-1)
我递归地编写了一种具有整个层次结构数据的方法-
require 'json'
def sort_tree_array(data, attr, asc = true)
data = data.is_a?(String) ? JSON.parse(data) : data
sorted = data.sort_by {|elem| [elem[attr]]}
sorted = asc ? sorted : sorted.reverse
sorted.each{ |item| item[:children] = sort_tree_array(item[:children], attr, asc) if (item[:children].nil? ? [] : item[:children]).size > 0 }
sorted
end
# Get the sorted array with ascending order name
p sort_tree_array(data, :name)
# Get the sorted array with descending order name
p sort_tree_array(data, :name, false)
# Get the sorted array with ascending order created_at_in_sec
p sort_tree_array(data, :created_at_in_sec)
# Get the sorted array with descending order created_at_in_sec
p sort_tree_array(data, :created_at_in_sec, false)