Javascript - It is possible to have a universal ordering function

Asked

Viewed 42 times

1

I have an object called report and I have a report vector and I need to do several sorts, so I thought I would do an ordering function that was "universal". I wanted to be able to pass the attribute to be ordered so that I could reuse the sorting function several times.

Object:

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

Sort function:

function ordena(vetor,attr) {
    vetor.sort(function(a,b) {
     return a.attr.localeCompare(b.attr);

    });
}

Example: By calling:

ordena(vetor,'ano');

I should have as a result the vector ordered by the year

By calling:

ordena(vetor,'titulo');

I should have as a result the vector ordered by the title

Is it possible? Or do I have to do a specific sorting function for each attribute?

  • In this case, "vector" in ordena(vetor,'ano');would be "report"?

1 answer

0

It is possible. You can use the bracket notation together with the parameter funcaoDeComparacao for the method sort(), where you should set the comparison function by accessing the object property within the array.

It may be so:

function ordenacaoDinamica(propriedade) {
    return function (a,b) {
        if (a[propriedade] < b[propriedade]) return -1;
        if (a[propriedade] > b[propriedade]) return 1;
        return 0;
    }
}

To invoke the function:

relatorios.sort(ordenacaoDinamica("ano"));
relatorios.sort(ordenacaoDinamica("titulo"));

If you want to see a working example, click on View code snippet below and then on Execute.

function ordenacaoDinamica(propriedade) {
    return function (a,b) {
        if (a[propriedade] < b[propriedade]) return -1;
        if (a[propriedade] > b[propriedade]) return 1;
        return 0;
    }
}

var relatorios = [
    {
        ano: '1990',
        sigla: 'ABC',
        veiculo: 'CD',
        qualis: 'FG',
        fator: 'HI',
        titulo: 'JK',
        autores: 'LM'
    },
    {
        ano: '1980',
        sigla: 'CDE',
        veiculo: 'FG',
        qualis: 'HI',
        fator: 'JK',
        titulo: 'LM',
        autores: 'NO'
    },
    {
        ano: '2010',
        sigla: 'AAA',
        veiculo: 'BBB',
        qualis: 'CCC',
        fator: 'DDD',
        titulo: 'EEE',
        autores: 'FFF'
    }
];

console.log(relatorios.sort(ordenacaoDinamica("ano")));
console.log(relatorios.sort(ordenacaoDinamica("titulo")));

Browser other questions tagged

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