Arrange array of objects according to one of their attributes

0

Well, that's how the title said, I wondered if I could sort how to sort%% of objects incrementally according to the value of an attribute given to it.

Example:

var objetos = []

var objeto1 {id:gerarId(), nome: nome1, idade: idade1}

var objeto2 {id:gerarId(), nome: nome2, idade: idade2}

objetos.push(objeto1);

objetos.push(objeto2);

And I kind of wanted to organize it in ascending order according to the age value.

Detail: I'm using array to store the data, and I want to do everything in javascript.

    
asked by anonymous 22.04.2017 / 23:19

1 answer

1

You should pass a comparison function as a parameter of sort :

objetos.sort(function(a, b) {
    return parseInt(a.idade) - parseInt(b.idade);
});

Reference: link

    
23.04.2017 / 17:48