How to use variable in Javascript Sort?

Asked

Viewed 87 times

1

I am doing a javascript sort from the Sort method, but I wonder if it is possible to use a variable to represent the attribute that will be used for sorting since this attribute may vary.

The code went like this:

msg.produtos.sort(function(a, b){

    if( a.valorProduto < b.valorProduto){
        return -1;
    }else if (a.valorProduto > b.valorProduto ){
        return 1;
    }
    return 0;    
});
return msg;

I imagined something like this:

let criterio;

criterio = msg.exemplo.criterio;//(supondo que o valor do atributo criterio fosse valorProduto).
msg.produtos.sort(function(a, b){

    if( a.criterio < b.criterio){
        return -1;
    }else if (a.criterio > b.criterio){
        return 1;
    }
    return 0;    
});
return msg;

But it didn’t work because he tries to find an attribute with the name "criterion" and not an attribute with the value within the criteria.

OBS: produto is an array of objects with the same attributes; The attribute that will be used as a criterion will vary and will be set at an earlier time.

Is there any way to make him use the value within the criterion variable or would have to do a if( criterio === x) and for each case mount a Sort with the attribute in question?

  • That would not be the case a[criterio] < b[criterio]? So you can access the property with the same name of the value that exists in the variable criterio.

  • I did the test, but it shows the following error: "Syntaxerror: Unexpected token [". É nodered

  • This syntax is valid, should not give unexpected token error. You did not put a dot or something like that before the bracket, put?

  • It worked!!! I didn’t take the . before the brackets so it didn’t work.

  • @user140828 gives an answer to the question get answer

1 answer

1

The doubt was solved according to the comments.

Solution: use the variable within [] and without the ".", getting:

let criterio;

criterio = msg.exemplo.criterio;//(supondo que o valor do atributo criterio fosse valorProduto).
msg.produtos.sort(function(a, b){

if( a[criterio] < b[criterio]){
    return -1;
}else if (a[criterio] > b[criterio]){
    return 1;
}
return 0;    
});
return msg;

Browser other questions tagged

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