Javascript - It is possible to have a universal sort function

1

I have an object called report and I have a report vector and need to do several sorts, so I thought I would do a sorting function that was "universal". I wanted to be able to pass the attribute to be sorted, so that I could reuse the sort 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: When calling:

ordena(vetor,'ano');

I should have the vector ordered by year

When calling:

ordena(vetor,'titulo');

I should have the vector ordered by title

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

    
asked by anonymous 20.11.2017 / 04:55

1 answer

0

It is possible. You can use the bracket notation together with the funcaoDeComparacao parameter for the sort() / a>, where you must define the comparison function by accessing the property of the object within array .

It may look like this:

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 an example working, click Show code snippet below and then Run .

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")));
    
20.11.2017 / 06:33