How to sort an array of objects by multiple fields?

后端 未结 30 2848
北恋
北恋 2020-11-21 11:34

From this original question, how would I apply a sort on multiple fields?

Using this slightly adapted structure, how would I sort city (ascending) & then price (

30条回答
  •  耶瑟儿~
    2020-11-21 12:22

    Here is a generic version of @Snowburnt's solution:

    var sortarray = [{field:'city', direction:'asc'}, {field:'price', direction:'desc'}];
    array.sort(function(a,b){
        for(var i=0; i b[sortarray[i].field] ? 1 : 0;
            if (sortarray[i].direction == "desc") {
                retval = retval * -1;
            }
            if (retval !== 0) {
                return retval;
            }
        }
    }
    
    
    })
    

    This is based on a sort routine I'm using. I didn't test this specific code so it may have errors but you get the idea. The idea is to sort based on the first field that indicates a difference and then stop and go to the next record. So, if you're sorting by three fields and the first field in the compare is enough to determine the sort order of the two records being sorted then return that sort result and go to the next record.

    I tested it (actually with a little more complex sort logic) on 5000 records and it did it in the blink of an eye. If you're actually loading more than 1000 records to the client you should probably be using sever-side sorting and filtering.

    This code isn't handling case-sensitivity but I leave it to the reader to handle this trivial modification.

提交回复
热议问题