How to sort an array of objects by multiple fields?

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

    function sortMultiFields(prop){
        return function(a,b){
            for(i=0;i b[field1])
                    return x;
                else if(a[field1] < b[field1])
                    return -x;
            }
        }
    }
    

    How to use (put -(minus) sign before field if you want to sort in descending order particular field)

    homes.sort(sortMultiFields(["city","-price"]));
    

    Using above function you can sort any json array with multiple fields. No need to change function body at all

提交回复
热议问题