Ordering object array by name

Asked

Viewed 73 times

0

Well I have an array of objects and I need to sort it by name. My array to follow:

COD_IDENT_PESSO: "120151202162147"
FLG_IDENT_PRESE: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "Renan Rodrigues Moraes"

COD_IDENT_PESSO: "120151202162542"
FLG_IDENT_PRESE: "L"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "Pedro Algusto"

COD_IDENT_PESSO: "120151202162836"
FLG_IDENT_PRESE: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "Andre Medeiros"

COD_IDENT_PESSO: "120151202162837"
FLG_IDENT_PRESE: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "Sousa Carvalho"

COD_IDENT_PESSO: "1151206095050177"
FLG_IDENT_PRESE: "L"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "Membro Sinc"

COD_IDENT_PESSO: "1151209082951928"
FLG_IDENT_PRESE: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "55555"

My code responsible for ordering:

for(var i = 0; i < arrayVelho.length; i++){
   if(arrayVelho[i].TXT_NOMEX_PESSO < nome){
       nome = arrayVelho[i].TXT_NOMEX_PESSO;
       arrayNovo = arrayVelho[i];
       arrayVelho[i].pop();
    }
}

But this logic that I used is not working, how to do ?

  • 6

    Here you can help, just adapt. http://answall.com/questions/100068/sort

  • Here’s another answer too. http://answall.com/questions/46600/howto sort and sort

  • Staff thank you very much, for me had different logic, but gave straight with what I wanted.

  • Found an answer to your question?

  • Yes thank you very much

2 answers

1

To sort objects use the function sort(), here is more information.

   arrayVelho.sort(function(a,b) {
        if(a.TXT_NOMEX_PESSO < b.TXT_NOMEX_PESSO) return -1;
        if(a.TXT_NOMEX_PESSO > b.TXT_NOMEX_PESSO) return 1;
        return 0;
    });

    for(var i = 0; i < arrayVelho.length; i++){
       if(arrayVelho[i].TXT_NOMEX_PESSO < nome){
           nome = arrayVelho[i].TXT_NOMEX_PESSO;
           arrayNovo = arrayVelho[i];
           arrayVelho[i].pop();
        }
    }

0

ORIGINAL ANSWER.

See Working.

    var objeto = [ 
    { data : new Date('11-30-2015'), nome: 'Marconi', telefone:'32486745425'},
    { data : new Date('11-31-2015'), nome: 'Marcos', telefone:'32486745425'},
    { data : new Date('11-25-2015'), nome: 'B', telefone:'32486745425'},
    { data : new Date('11-27-2015'), nome: 'Testes', telefone:'32486745425'},
];
 			
function compare(a,b) {
  return a.nome < b.nome;
}

console.log(objeto.sort(compare));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.