Problem in array ordering with numerical values in VUE?

Asked

Viewed 41 times

1

I have the code below that I am using to sort an array, in field with the format String is working normally, as I must to sort numeric field?

list_cob_frequencia() {
    var campo = 'nome_campo';
    var ordem = 'ASC';
    return this.json_cobertura_frequencia.slice().sort(function(a, b) {
        if (ordem == 'ASC') {
            return (a[campo] < b[campo]) ? 1 : -1;
        } else {
            return (b[campo] < a[campo]) ? 1 : -1;
        }
    });
}
  • Has there been any response ?

1 answer

0

To sort number the example below already clarifies your doubt:

var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return a-b});
document.getElementById("demoO").innerHTML = points;
<div id="demo"></div>
<hr />
<div id="demoO"></div>

In your code something like this:

list_cob_frequencia() {
    var campo = 'nome_campo';
    var ordem = 'ASC';   
    return this.json_cobertura_frequencia.slice().sort(function(a, b) {
        if (ordem == 'ASC') {
            return (a[campo] - b[campo]);
        } else {
            return (b[campo] - a[campo]);
        }
    });
}

Observing: the field to be done the operation must be a number and if you need some conversion use parseint.

Reference: Javascript Array Sort() Method

Browser other questions tagged

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