Reputation: 1309
Basically I have about 36 variables that are named t0, t1, t3 ... and so on, each variable is initiated with the value 0, and depending on actions they get incremented by 1.
I want a way to be able to list the top ten highest valued variables ideally by putting them in an array like Var topTen = [t33,t31,t2].
Upvotes: 0
Views: 2603
Reputation: 4053
res = [{k:"t1",v:t1},{k:"t2",v:t2},...,{k:"t36",v:t36}].sort(
function(a,b){
return b.v-a.v
}).map(function(x){return x.k}).slice(0,9)
btw. you can create the array dynamically if the variables are represented as object properties... if you need the values, then return x.v instead of x.k
Upvotes: 1
Reputation: 56
Should try this method :
var myarray=["t14", "t53", "t1"]
myarray.sort();
myarray.reverse();
var final = myarray.slice(0,10);
//SHOULD GIVE YOU
// ["t53", "t14", "t1"]
Then you can extract the ten first value.
UPDATE --> JSFiddle
Upvotes: 1
Reputation: 25892
Sort your array after that slice
first 10 elements.
arr.sort(function (a,b) {
return a - b;
});
var result = arr.slice(0,10);
Upvotes: 0
Reputation: 63550
Why don't you use an object to store the information - instead of 36 variables have just one object with 36 properties. Then you can loop through the values, add them to an array and grab the set of numbers you need:
var obj = {
t1: 1,
t2: 33,
t3: 10,
t4: 9,
t5: 45,
t6: 101,
...
}
// create an array
var arr = [];
// loop through the object and add values to the array
for (var p in obj) {
arr.push(obj[p]);
}
// sort the array, largest numbers to lowest
arr.sort(function(a,b){return b - a});
// grab the first 10 numbers
var firstTen = arr.slice(0, 9);
This will return an array - just loop through it to list the values one by one.
Upvotes: 1
Reputation: 1550
First put the variables in an array:
var ts = [t0, t1, ...];
You can then get the top 10 like this:
var topTen = ts.sort().slice(-10).reverse();
Ideally you want store all your values in an array in the first place.
Upvotes: 0