Problems with sorting by more than one criterion

0

In java we have the possibility to overwrite the compareTo function of a class and use sort () to sort a vector of objects. I would like to do the same with JavaScript, I already know I could use this sort function call but I am not able to adapt the function below in the sort. I think it's because I want to use more than one sorting criterion.

I have an object of the report type, with the following properties: I want to order by qualis, and then by year. When I try to call the sort order 2 times, it re-sorts for the year and ignores the sort order.

var relatorio = {
        ano: '',
        sigla: '',
        veiculo: '',
        qualis: '',
        fator: '',
        titulo: '',
        autores: ''
    };

Function call:

Relatorio.sort(ordenacaoDinamica());

Function I'm trying:

function teste(){
        var propriedade = 'qualis';
        return function (a,b) {
            if (a[propriedade] < b[propriedade]){
                return -1;
            } 
            if (a[propriedade] > b[propriedade]){
                return 1;
            }
            else{
                propriedade = 'ano';
                if (a[propriedade] > b[propriedade]){
                    return -1;
                } 
                if (a[propriedade] < b[propriedade]){
                    return 1;
                }
            }
            return 0;
        }
    }
    
asked by anonymous 05.12.2017 / 19:19

2 answers

1

Like the way you were doing with if , you can check that qualis is the same as the other, if it is you check the year.

In javascript you can take advantage of the fact that the value 0 is interpreted with false to do:

let ordenacao = comparacaoDoQualis || comparacaoDoAno;

Here is an example of the sort function:

let relatorio = [
    {'ano': '2020', 'qualis': 'B2'},
    {'ano': '2017', 'qualis': 'A2'},
    {'ano': '2017', 'qualis': 'B2'},
    {'ano': '2018', 'qualis': 'A3'},
    {'ano': '2017', 'qualis': 'A3'},
    {'ano': '2018', 'qualis': 'B1'},
    {'ano': '2015', 'qualis': 'B2'},
];


relatorio.sort((a, b) => {
   let qualis = (a.qualis == b.qualis) ? 0 : ((a.qualis > b.qualis) ? 1 : -1);
   let ano = (a.ano == b.ano) ? 0 : ((a.ano > b.ano) ? 1 : -1);

   //se o qualis for 0 ele retorna o valor da comparação do ano
   return qualis || ano;
});

console.log(relatorio);
    
05.12.2017 / 22:24
0

Try this:

const data = [
    { qualis: 'A1', ano: '2017' },
    { qualis: 'A1', ano: '2014' },
    { qualis: 'A2', ano: '2011' },
    { qualis: 'A3', ano: '2012' },
    { qualis: 'A6', ano: '2019' },
    { qualis: 'A9', ano: '2020' },
];

function sortData(data) {
  return data.slice().sort((o1, o2) => {
    const qualis = o1.qualis.localeCompare(o2.qualis);
    
    if (qualis !== 0) {
      return qualis;
    }
    
    const ano = o1.ano.localeCompare(o2.ano);
    
    return ano;
  });
}

const sortedData = sortData(data);

console.log(sortedData);
    
05.12.2017 / 23:58