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 variablecriterio
.– Andre
I did the test, but it shows the following error: "Syntaxerror: Unexpected token [". É nodered
– MathN
This syntax is valid, should not give unexpected token error. You did not put a dot or something like that before the bracket, put?
– Andre
It worked!!! I didn’t take the . before the brackets so it didn’t work.
– MathN
@user140828 gives an answer to the question get answer
– Sergio