简体   繁体   中英

How to sort an object array by two different values

I have an object array

var arr= [  {vara:4, varb:0, varc:3}    {vara:1, varb:2, varc:0}    {vara:3, varb:1, varc:5} ..... ]

At first i want to sort the array by vara so i use

arr.sort(function(a, b){return a.vara-b.vara});

If the sorted array have equal values in vara parameter, i want to do a second sorting by varb that will only resort the objects with equal vara values and not all the array.

How is this possible?

How about something like:

arr.sort(function(a, b){
    if (a.vara === b.vara) {
        return a.varb - b.varb
    }
    return a.vara-b.vara;
});

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