Reputation: 107
I use this code to sort table values:
var t1 = 6;
var t2 = 2;
var t3 = 4;
var t4 = 1;
var t5 = 3;
var t6 = 5;
var points = [t1, t2, t3, t4, t5, t6];
points.sort(function(a, b) { return a - b });
This returns: 1,2,3,4,5,6
This sort
method works fine but how to updated the sorted values to the variables in that order? Like, least value should be assigned to t1
, second least to t2
,...and max value to t6
?
Upvotes: 1
Views: 413
Reputation: 35243
You could use array destructuring to assign the sorted values back to the variables:
var t1 = 6;
var t2 = 2;
var t3 = 4;
var t4 = 1;
var t5 = 3;
var t6 = 5;
var points = [t1, t2, t3, t4, t5, t6];
[t1, t2, t3, t4, t5, t6] = points.sort(function(a, b) { return a - b })
console.log(t1, t2, t3, t4, t5, t6)
Now, the first value from sorted array will be assigned to t1
, second value to t2
etc.
Upvotes: 1