0

I am with the following problem:

I try to sort a list of persons containing the flag that identifies the person (pupil or teacher), the code of the person, the name of the person, the status of the person (active, inactive, blocked) and the status of the participation in that room (active, inactive and locked), all this information within a vector that I call the arrayVelhoAux. Here I want to sort this vector alphabetically (A,B,C,D,E, ...).

arrayVelhoAux.FLG_IDENT_PESSO = arrayCursor[j].FLG_IDENT_PESSO;
arrayVelhoAux.COD_IDENT_PESSO = pessoa.COD_IDENT_PESSO;
arrayVelhoAux.TXT_NOMEX_PESSO = pessoa.TXT_NOMEX_PESSO;
arrayVelhoAux.FLG_STATU_PESSO = pessoa.FLG_STATU_PESSO;
arrayVelhoAux.FLG_STATU_PARTC = arrayCursor[j].FLG_STATU_PARTC;

arrayVelho.push(arrayVelhoAux);

For completing this vector am I doing a loop, because there are data that caught in other tables.After the total fulfillment of this vector i do a .sort() with the purpose of ordering it.

arrayVelho.sort(compareArray);

In compareArray function simply phenonmenon which is greater. By placing all letters uppercase to which all are compared in the same size.

function compareArray(a1,b1) {
    if(a1.TXT_NOMEX_PESSO.toUpperCase() > b1.TXT_NOMEX_PESSO.toUpperCase()) return 1;
    if(a1.TXT_NOMEX_PESSO.toUpperCase() < b1.TXT_NOMEX_PESSO.toUpperCase()) return -1;
    return 0;
}

Apparently there is nothing wrong and something interesting happens because, os is comparing some, others are out of order. As in the following image.

Problems with the ordination of a list of array

I would like to know if there is any better solution that is, or if would confer and leave this solution 100% functional.

CupawnTae
  • 14,192
  • 3
  • 29
  • 60
Renan Rodrigues
  • 286
  • 1
  • 4
  • 22
  • to fix your new version, just switch the `<` and `>` (or the `1` and `-1`). However, your code now doesn't match your question, so I would suggest you revert the question to the previous version to make it less confusing for readers – CupawnTae Apr 08 '16 at 12:50

2 Answers2

3

Callback function for sort function should return -1 (or less than 0) or 1 (or greater than 0) or 0.

Because your return boolean value it's considered either 1 or 0 and never -1. That's why your sorting is sometimes wrong.

More info here https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

You can use localeCompare to compare strings with the right return values for sort as follows:

function compareArray(a1,b1) {
  return a1.TXT_NOMEX_PESSO.toUpperCase()
    .localeCompare( b1.TXT_NOMEX_PESSO.toUpperCase() );
}
CupawnTae
  • 14,192
  • 3
  • 29
  • 60