Problems with array.sort ()

1

I'm trying to sort an array but I'm having trouble, it's just returning 0. I'm doing the following:

Here I draw my array:

arrayVelho.sort(compare);

After calling the compare function that compares the array data:

function compare(a,b) {

//return a.TXT_NOMEX_PESSO < b.TXT_NOMEX_PESSO;
var valorA = ((a.TXT_NOMEX_PESSO == null)? "Z": a.TXT_NOMEX_PESSO),
    valorB = ((b.TXT_NOMEX_PESSO == null)? "Z": b.TXT_NOMEX_PESSO);

var respA = valorA.toUpperCase(),
    respB = valorB.toUpperCase();

        console.log(respA + " - " + respB);
    console.log(respA.TXT_NOMEX_PESSO > respB.TXT_NOMEX_PESSO ? -1 : respA.TXT_NOMEX_PESSO < respB.TXT_NOMEX_PESSO ? 1 : 0);
    return respA.TXT_NOMEX_PESSO > respB.TXT_NOMEX_PESSO ? -1 : respA.TXT_NOMEX_PESSO < respB.TXT_NOMEX_PESSO ? 1 : 0;
}

The result of console.log () looks like this:

HADAILTON DE SOUSA CARVALHO - RENAN RODRIGUES MORAES main.js:1350
0 main.js:1351
RENAN RODRIGUES MORAES - TESTESS main.js:1350
0 main.js:1351
TESTESS - ANTONIO main.js:1350
0 main.js:1351
ANTONIO - BACHINHO main.js:1350
0 main.js:1351
BACHINHO - CASA DE CARNE main.js:1350
0 

The structure of my array is:

arrayVelho[Object, Object, Object, Object, Object, Object]

0: Object
COD_IDENT_PESSO: "3"
FLG_IDENT_PESSO: "L"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "HADAILTON DE SOUSA CARVALHO"
---------------
1: Object
COD_IDENT_PESSO: "4"
FLG_IDENT_PESSO: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "RENAN RODRIGUES MORAES"
---------------
2: Object
COD_IDENT_PESSO: "3160127100149523"
FLG_IDENT_PESSO: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "testess"
_---------------
3: Object
COD_IDENT_PESSO: "3160127100725576"
FLG_IDENT_PESSO: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "Antonio"
----------------
4: Object
COD_IDENT_PESSO: "3160127100908469"
FLG_IDENT_PESSO: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "bachinho"
----------------
5: Object
COD_IDENT_PESSO: "3160127100924955"
FLG_IDENT_PESSO: "M"
FLG_STATU_PESSO: "A"
TXT_NOMEX_PESSO: "casa de carne"

It should be sorted alphabetically, I can not predict, because this array is for all people, it can have 5 people as it can be 20.

What am I doing wrong? And how to put in alphabetical order?

    
asked by anonymous 27.01.2016 / 13:29

1 answer

2

It can not sort correctly when it has uppercase and lowercase values.

So you just have to use the toUpperCase() function to put all the text in Maiúsculo and compare, or if you want to use toLowerCase() that makes all text Minúsculo . This question follows the table of reasoning this adapt. See:

var array = [ 
    {TXT_NOMEX_PESSO: 'HADAILTON DE SOUSA CARVALHO'},
    {TXT_NOMEX_PESSO: 'RENAN RODRIGUES MORAES'},
    {TXT_NOMEX_PESSO: 'testess'},
    {TXT_NOMEX_PESSO: 'Antonio'},
    {TXT_NOMEX_PESSO: 'bachinho'},
    {TXT_NOMEX_PESSO: 'casa de carne'}
];
 			
function compare(a,b) {
  return a.TXT_NOMEX_PESSO.toUpperCase() > b.TXT_NOMEX_PESSO.toUpperCase();
}

console.log(array.sort(compare));
    
27.01.2016 / 13:57