Consider the following data structure:
var set = [
{
"name":"alpha",
"require":[]
},
{
"name":"beta",
"require":["echo"]
},
{
"name":"charlie",
"require":[]
},
{
"name":"delta",
"require":["charlie", "beta"]
},
{
"name":"echo",
"require":[]
}
];
The task is to sort items based on multiple requirements, where items with dependencies should come after all the items they depend on. An example output for the given sample data would be:
alpha, charlie, echo, beta, delta
While the Array.sort method https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort can be used, understanding how to implement sorting based on multiple requirements may be challenging.
An attempt using a comparison function:
set.sort(function (a, b) {
return a.name > b.require[0] ? 1 : -1;
});
-- Revised based on @hindmost's response --
However, the above approach may not always produce the desired result. Consider a new set of sample data:
var set = [
{
"name":"zzz",
"require":["xxx"]
},
{
"name":"xxx",
"require":["yyy"]
},
{
"name":"fff",
"require":[]
},
{
"name":"yyy",
"require":["fff", "kkk"]
},
{
"name":"kkk",
"require":[]
}
];
This input yields:
fff, kkk, xxx, zzz, yyy
Instead, the expected outcome is:
fff, kkk, yyy, xxx, zzz
To clarify, the sorting should not solely rely on alphabetical order or the length of the require array, but rather ensure that an item depending on others comes after its dependencies in the final sequence.