简体   繁体   中英

Sorting on multiple attributes with parent/child relationship

I have a an array of objects:

    a {bindSortorder: 4, bindParentid: -1, bindQuestionid: 371}
    b {bindSortorder: 2, bindParentid: -1, bindQuestionid: 800}
    c {bindSortorder: 4, bindParentid: 23, bindQuestionid: 123}
    d {bindSortorder: 1, bindParentid: -1, bindQuestionid: 371}
    e {bindSortorder: 4, bindParentid: 371, bindQuestionid: 456}
    f {bindSortorder: 3, bindParentid: -1, bindQuestionid: 371}
    g {bindSortorder: 2, bindParentid: 800, bindQuestionid: 223}

I need to sort them in the following structure:

Sortorder

  • Parent

    • Child (Questionid)

...so that the above example would result in the following order:

dbgfaec

If it's necessary for the "-1" denoting a parent to be changed to some other value, I'm open to that. I was just trying to take it out of the sort equation by making sure it could not equal an actual Questionid.

I've written the following which successfully prioritizes the sort order and groups the children together....but they are not grouped under their respective parents. All of the parents are grouped together, however.

    return (aSortorder < bSortorder ? -1 : (aSortorder > bSortorder) ? 1 : ((aParentid < bParentid) ? -1 : ((aParentid > bParentid) ? 1 : 0)));

Any help would be appreciated. Thanks

Here's how I solved it:

SortQuestionsByParent:function(a,b){
    var aElm = $(a).data();
    var bElm = $(b).data();     
    var aParent = aElm.bindParentid;
    var bParent = bElm.bindParentid;
    var aQuestionId = aElm.bindQuestionid;
    var bQuestionId = bElm.bindQuestionid;
    var aOrder = aElm.bindSortorder;
    var bOrder = bElm.bindSortorder;
    var aTempId;
    var bTempId;
    (aParent < 0) ? aTempId = aQuestionId + ".5" : aTempId = aParent + ".9";
    (bParent < 0) ? bTempId = bQuestionId + ".5" : bTempId = bParent + ".9";
    var result = aOrder - bOrder || aTempId - bTempId;
    console.log(result);        
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM