1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

An explanation would certainly be helpful as well.
Question updated to add another sample, result and further explanation.
Actually I've misunderstood your problem. So it cannot be solved by Array's sort method. The only solution in this case is using recursion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.