Sort array of objects by 2 attributes in JavaScript

2

I would like to sort an array of objects by two attributes.

The array is as follows:

var unidades = [{"id": 1, "numero": 3, "bloque": "F"},
                {"id": 2, "numero": 101, "bloque": "A"},
                {"id": 1, "numero": 1, "bloque": "F"},
                {"id": 1, "numero": 5, "bloque": "C"},
                {"id": 1, "numero": 1, "bloque": "A"}

];

I want to sort the array first by block and then by number, ascending. How can I do it ? Now I have a function that only orders me by block, but I need the number, which is the following:

function ordenarBloque(a,b) {
            if (a.bloque < b.bloque)
                return -1;
            else if (a.bloque > b.bloque)
                return 1;
            else 
                return 0;
        };

Any suggestions?

Thank you.

    
asked by jam1981 17.08.2016 в 18:19
source

1 answer

2

It's a matter of adding the second comparison when the first field is the same:

function ordenarBloque(a,b) {
        if (a.bloque < b.bloque)
            return -1;
        else if (a.bloque > b.bloque)
            return 1;
        else 
            if (a.numero< b.numero)
                return -1;
            else if (a.numero> b.numero)
                return 1;
            else 
                return 0;
    };
    
answered by 17.08.2016 / 19:11
source