Sort objects in array by multiple property (possibility does not exist)












0















I am trying to sort this array:



[
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
]


As you can see, there are object who doesn't have parentId. I need to keep this one on the top and the rest will be sorted by id.



Here's my code:



input.sort(function (a, b) {
if (typeof a.parentId === 'undefined'))
return -1;
else
return a.id - b.id;
});


It doesn't work though. Is it possible to do this?



Expected result:



[
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
},
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
}
]


Thanks in advance










share|improve this question























  • if sorting in descending order then in expected result parentId 877234003 will come first then parentId 877234003. pls edit your question.

    – Shiv Kumar Baghel
    Jan 2 at 5:32


















0















I am trying to sort this array:



[
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
]


As you can see, there are object who doesn't have parentId. I need to keep this one on the top and the rest will be sorted by id.



Here's my code:



input.sort(function (a, b) {
if (typeof a.parentId === 'undefined'))
return -1;
else
return a.id - b.id;
});


It doesn't work though. Is it possible to do this?



Expected result:



[
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
},
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
}
]


Thanks in advance










share|improve this question























  • if sorting in descending order then in expected result parentId 877234003 will come first then parentId 877234003. pls edit your question.

    – Shiv Kumar Baghel
    Jan 2 at 5:32
















0












0








0








I am trying to sort this array:



[
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
]


As you can see, there are object who doesn't have parentId. I need to keep this one on the top and the rest will be sorted by id.



Here's my code:



input.sort(function (a, b) {
if (typeof a.parentId === 'undefined'))
return -1;
else
return a.id - b.id;
});


It doesn't work though. Is it possible to do this?



Expected result:



[
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
},
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
}
]


Thanks in advance










share|improve this question














I am trying to sort this array:



[
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
]


As you can see, there are object who doesn't have parentId. I need to keep this one on the top and the rest will be sorted by id.



Here's my code:



input.sort(function (a, b) {
if (typeof a.parentId === 'undefined'))
return -1;
else
return a.id - b.id;
});


It doesn't work though. Is it possible to do this?



Expected result:



[
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
},
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
}
]


Thanks in advance







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 5:19









wowhcumoswowhcumos

32




32













  • if sorting in descending order then in expected result parentId 877234003 will come first then parentId 877234003. pls edit your question.

    – Shiv Kumar Baghel
    Jan 2 at 5:32





















  • if sorting in descending order then in expected result parentId 877234003 will come first then parentId 877234003. pls edit your question.

    – Shiv Kumar Baghel
    Jan 2 at 5:32



















if sorting in descending order then in expected result parentId 877234003 will come first then parentId 877234003. pls edit your question.

– Shiv Kumar Baghel
Jan 2 at 5:32







if sorting in descending order then in expected result parentId 877234003 will come first then parentId 877234003. pls edit your question.

– Shiv Kumar Baghel
Jan 2 at 5:32














2 Answers
2






active

oldest

votes


















1














Need to test A and B and invert. if A is missing the prop use -1 if B use +1






let arr = [{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
];

const sortPredicate = (a,b) => {
if (a.hasOwnProperty('parentId') === false) {
return -1;
} else if(b.hasOwnProperty('parentId') === false) {
return 1;
} else {
return a.id - b.id;
}
};


console.log(arr.sort(sortPredicate));








share|improve this answer
























  • beautiful, thanks master!

    – wowhcumos
    Jan 2 at 5:41











  • An possible optimization would be to return the difference between each hasOwnProperty check.

    – CertainPerformance
    Jan 2 at 9:29



















2














i would suggest to use lodash js library






var arr = [
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
];

var sortedArr = _.orderBy(arr, 'parentId', 'desc');

console.log(sortedArr);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54001558%2fsort-objects-in-array-by-multiple-property-possibility-does-not-exist%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Need to test A and B and invert. if A is missing the prop use -1 if B use +1






    let arr = [{
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    const sortPredicate = (a,b) => {
    if (a.hasOwnProperty('parentId') === false) {
    return -1;
    } else if(b.hasOwnProperty('parentId') === false) {
    return 1;
    } else {
    return a.id - b.id;
    }
    };


    console.log(arr.sort(sortPredicate));








    share|improve this answer
























    • beautiful, thanks master!

      – wowhcumos
      Jan 2 at 5:41











    • An possible optimization would be to return the difference between each hasOwnProperty check.

      – CertainPerformance
      Jan 2 at 9:29
















    1














    Need to test A and B and invert. if A is missing the prop use -1 if B use +1






    let arr = [{
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    const sortPredicate = (a,b) => {
    if (a.hasOwnProperty('parentId') === false) {
    return -1;
    } else if(b.hasOwnProperty('parentId') === false) {
    return 1;
    } else {
    return a.id - b.id;
    }
    };


    console.log(arr.sort(sortPredicate));








    share|improve this answer
























    • beautiful, thanks master!

      – wowhcumos
      Jan 2 at 5:41











    • An possible optimization would be to return the difference between each hasOwnProperty check.

      – CertainPerformance
      Jan 2 at 9:29














    1












    1








    1







    Need to test A and B and invert. if A is missing the prop use -1 if B use +1






    let arr = [{
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    const sortPredicate = (a,b) => {
    if (a.hasOwnProperty('parentId') === false) {
    return -1;
    } else if(b.hasOwnProperty('parentId') === false) {
    return 1;
    } else {
    return a.id - b.id;
    }
    };


    console.log(arr.sort(sortPredicate));








    share|improve this answer













    Need to test A and B and invert. if A is missing the prop use -1 if B use +1






    let arr = [{
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    const sortPredicate = (a,b) => {
    if (a.hasOwnProperty('parentId') === false) {
    return -1;
    } else if(b.hasOwnProperty('parentId') === false) {
    return 1;
    } else {
    return a.id - b.id;
    }
    };


    console.log(arr.sort(sortPredicate));








    let arr = [{
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    const sortPredicate = (a,b) => {
    if (a.hasOwnProperty('parentId') === false) {
    return -1;
    } else if(b.hasOwnProperty('parentId') === false) {
    return 1;
    } else {
    return a.id - b.id;
    }
    };


    console.log(arr.sort(sortPredicate));





    let arr = [{
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    const sortPredicate = (a,b) => {
    if (a.hasOwnProperty('parentId') === false) {
    return -1;
    } else if(b.hasOwnProperty('parentId') === false) {
    return 1;
    } else {
    return a.id - b.id;
    }
    };


    console.log(arr.sort(sortPredicate));






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 2 at 5:32









    BibbertyBibberty

    1,9431315




    1,9431315













    • beautiful, thanks master!

      – wowhcumos
      Jan 2 at 5:41











    • An possible optimization would be to return the difference between each hasOwnProperty check.

      – CertainPerformance
      Jan 2 at 9:29



















    • beautiful, thanks master!

      – wowhcumos
      Jan 2 at 5:41











    • An possible optimization would be to return the difference between each hasOwnProperty check.

      – CertainPerformance
      Jan 2 at 9:29

















    beautiful, thanks master!

    – wowhcumos
    Jan 2 at 5:41





    beautiful, thanks master!

    – wowhcumos
    Jan 2 at 5:41













    An possible optimization would be to return the difference between each hasOwnProperty check.

    – CertainPerformance
    Jan 2 at 9:29





    An possible optimization would be to return the difference between each hasOwnProperty check.

    – CertainPerformance
    Jan 2 at 9:29













    2














    i would suggest to use lodash js library






    var arr = [
    {
    "id": 877234004,
    "name": "app.js",
    "type": "FILE",
    "parentId": 877234003
    },
    {
    "id": 877234010,
    "name": "project",
    "type": "DIRECTORY"
    },
    {
    "id": 877234002,
    "name": "src",
    "type": "DIRECTORY",
    "parentId": 877234010
    },
    {
    "id": 877234003,
    "name": "app",
    "type": "DIRECTORY",
    "parentId": 877234002
    }
    ];

    var sortedArr = _.orderBy(arr, 'parentId', 'desc');

    console.log(sortedArr);

    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








    share|improve this answer






























      2














      i would suggest to use lodash js library






      var arr = [
      {
      "id": 877234004,
      "name": "app.js",
      "type": "FILE",
      "parentId": 877234003
      },
      {
      "id": 877234010,
      "name": "project",
      "type": "DIRECTORY"
      },
      {
      "id": 877234002,
      "name": "src",
      "type": "DIRECTORY",
      "parentId": 877234010
      },
      {
      "id": 877234003,
      "name": "app",
      "type": "DIRECTORY",
      "parentId": 877234002
      }
      ];

      var sortedArr = _.orderBy(arr, 'parentId', 'desc');

      console.log(sortedArr);

      <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








      share|improve this answer




























        2












        2








        2







        i would suggest to use lodash js library






        var arr = [
        {
        "id": 877234004,
        "name": "app.js",
        "type": "FILE",
        "parentId": 877234003
        },
        {
        "id": 877234010,
        "name": "project",
        "type": "DIRECTORY"
        },
        {
        "id": 877234002,
        "name": "src",
        "type": "DIRECTORY",
        "parentId": 877234010
        },
        {
        "id": 877234003,
        "name": "app",
        "type": "DIRECTORY",
        "parentId": 877234002
        }
        ];

        var sortedArr = _.orderBy(arr, 'parentId', 'desc');

        console.log(sortedArr);

        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








        share|improve this answer















        i would suggest to use lodash js library






        var arr = [
        {
        "id": 877234004,
        "name": "app.js",
        "type": "FILE",
        "parentId": 877234003
        },
        {
        "id": 877234010,
        "name": "project",
        "type": "DIRECTORY"
        },
        {
        "id": 877234002,
        "name": "src",
        "type": "DIRECTORY",
        "parentId": 877234010
        },
        {
        "id": 877234003,
        "name": "app",
        "type": "DIRECTORY",
        "parentId": 877234002
        }
        ];

        var sortedArr = _.orderBy(arr, 'parentId', 'desc');

        console.log(sortedArr);

        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>








        var arr = [
        {
        "id": 877234004,
        "name": "app.js",
        "type": "FILE",
        "parentId": 877234003
        },
        {
        "id": 877234010,
        "name": "project",
        "type": "DIRECTORY"
        },
        {
        "id": 877234002,
        "name": "src",
        "type": "DIRECTORY",
        "parentId": 877234010
        },
        {
        "id": 877234003,
        "name": "app",
        "type": "DIRECTORY",
        "parentId": 877234002
        }
        ];

        var sortedArr = _.orderBy(arr, 'parentId', 'desc');

        console.log(sortedArr);

        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>





        var arr = [
        {
        "id": 877234004,
        "name": "app.js",
        "type": "FILE",
        "parentId": 877234003
        },
        {
        "id": 877234010,
        "name": "project",
        "type": "DIRECTORY"
        },
        {
        "id": 877234002,
        "name": "src",
        "type": "DIRECTORY",
        "parentId": 877234010
        },
        {
        "id": 877234003,
        "name": "app",
        "type": "DIRECTORY",
        "parentId": 877234002
        }
        ];

        var sortedArr = _.orderBy(arr, 'parentId', 'desc');

        console.log(sortedArr);

        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 2 at 5:33

























        answered Jan 2 at 5:28









        Shiv Kumar BaghelShiv Kumar Baghel

        1,4263921




        1,4263921






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54001558%2fsort-objects-in-array-by-multiple-property-possibility-does-not-exist%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith