How to sort an array of objects by multiple fields?

后端 未结 30 2324
北恋
北恋 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:21

    This is a recursive algorithm to sort by multiple fields while having the chance to format values before comparison.

    var data = [
    {
        "id": 1,
        "ship": null,
        "product": "Orange",
        "quantity": 7,
        "price": 92.08,
        "discount": 0
    },
    {
        "id": 2,
        "ship": "2017-06-14T23:00:00.000Z".toDate(),
        "product": "Apple",
        "quantity": 22,
        "price": 184.16,
        "discount": 0
    },
    ...
    ]
    var sorts = ["product", "quantity", "ship"]
    
    // comp_val formats values and protects against comparing nulls/undefines
    // type() just returns the variable constructor
    // String.lower just converts the string to lowercase.
    // String.toDate custom fn to convert strings to Date
    function comp_val(value){
        if (value==null || value==undefined) return null
        var cls = type(value)
        switch (cls){
            case String:
                return value.lower()
        }
        return value
    }
    
    function compare(a, b, i){
        i = i || 0
        var prop = sorts[i]
        var va = comp_val(a[prop])
        var vb = comp_val(b[prop])
    
        // handle what to do when both or any values are null
        if (va == null || vb == null) return true
    
        if ((i < sorts.length-1) && (va == vb)) {
            return compare(a, b, i+1)
        } 
        return va > vb
    }
    
    var d = data.sort(compare);
    console.log(d);
    

    If a and b are equal it will just try the next field until none is available.

提交回复
热议问题