hacker tom
hacker tom

Reputation: 107

Sort an array of variables and assign them the sorted value

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

Answers (1)

adiga
adiga

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

Related Questions