I have this array of Hash:
hash =
[
{
distance: 0.3997651063189804, project_id: 1, project_name: "Project 1", project_dependents_ids: [4]
},
{
distance: 0.414026818885287, project_id: 2, project_name: "Project 2", project_dependents_ids: [1]
},
{
distance: 0.6259577862775509, project_id: 3, project_name: "Project 3", project_dependents_ids: []
},
{
distance: 0.43719371056189227, project_id: 4, project_name: "Project 4", project_dependents_ids: [3]
},
{
distance: 0.4341702282185951, project_id: 5, project_name: "Project 5", project_dependents_ids: []
}
]
I have to sort it by distance first, BUT, if the project has project_dependents (self association), it must comes after the project associated.
Ex:
A simple sort by distances, as below:
hash.sort! { |a, b| b[:distance] <=> a[:distance] }
... will result in:
- Project 3
- Project 4
- Project 5
- Project 2
- Project 1
But this result isn't 100% what I want. I want to sort it also by the project_dependents. Ex:
The result must be:
- Project 3
- Project 4
- Project 5
- Project 1 # Project 1 has less distance, BUT project 2 depends of it.
- Project 2
It's just a simple example. A project can have many self association ids and so on..
So, I want to know how I can implement this kind of sort. Maybe a general idea would be helpful. All the implementations that I made here got giant code and incorrect result.
order), not withsort.dataisn't coming from my database. This is the result of some math calculations that I did in mycontroller. I just got stucked with this, it's a bit complex.:project_dependents_idsare empty arrays or arrays containing a single dependent id. The name of the key suggests those arrays may contain more than one dependent id. Can they? 2. Can the ids be such that 2 must follow 1, 3 must follow 2 and 1 must follow 3 (in which case that impossibility would have to be identified in code)? This is not an easy problem.:project_dependents_idscan contain more than one dependent. 2. Well, it's a problem (a circular dependence) that I've already solved (or I think I've solved) before do this kind of sort. Yes, I know it isn't an easy problem, that's why I'm stucked :(