Reputation: 11
Given this data structure:
var set = [
{
"name":"alpha",
"require":[]
},
{
"name":"beta",
"require":["echo"]
},
{
"name":"charlie",
"require":[]
},
{
"name":"delta",
"require":["charlie", "beta"]
},
{
"name":"echo",
"require":[]
}
];
Items should be sorted based on possible multiple require's where items with requires should be below all items in the required property. A possible output from the sample data above is:
alpha, charlie, echo, beta, delta
I understand there is a Array.sort method https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort but I don't understand the algorithm to sort based on multiple requirements.
As I have done this before:
set.sort(function (a, b) {
return a.name > b.require[0] ? 1 : -1;
});
-- EDIT for @hindmost answer --
Although this gets the expected output it doesn't work as expected. Consider this 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":[]
}
];
Which results in:
fff, kkk, xxx, zzz, yyy
Expected:
fff, kkk, yyy, xxx, zzz
Explanation: The sorting is not based on alphabetical name order or require array length but if yyy requires fff and kkk, then yyy must be later in the array then both fff and kkk. Where zzz requires xxx and xxx requires yyy, then xxx must be after yyy and zzz after xxx.
Upvotes: 1
Views: 158
Reputation: 7195
Try this:
set.sort(function (a, b) {
return a.require.length == b.require.length ?
(a.name < b.name ? -1 : 1) :
(a.require.length < b.require.length ? -1 : 1);
});
Explanation:
First we compare elements by require
prop and return -1
(1st < 2nd) or 1
(1st > 2nd). Secondly, if values of require
are equal we compare by name
prop in similar manner.
Upvotes: 1