admin 管理员组

文章数量: 1087134

so I use JavaScript and I have an array of variables.

var a=5,b=10,c=3,d=11,e=0; //5 Variables with randomly chosen values
var myArray=[a,b,c,d,e]; 
myArray.sort(); //sort them, so the lowest value or variable is on first place
alert("This Variable has the lowest value: " + myArray[0]); 
//tell me the variable with the lowest value

So basically, i will get this text: "This Variable has the lowest value: 0"

But what i want is: "This Variable has the lowest value: e"

How can i return the variable, instead of the value of the variable?

Best Regards qweret

so I use JavaScript and I have an array of variables.

var a=5,b=10,c=3,d=11,e=0; //5 Variables with randomly chosen values
var myArray=[a,b,c,d,e]; 
myArray.sort(); //sort them, so the lowest value or variable is on first place
alert("This Variable has the lowest value: " + myArray[0]); 
//tell me the variable with the lowest value

So basically, i will get this text: "This Variable has the lowest value: 0"

But what i want is: "This Variable has the lowest value: e"

How can i return the variable, instead of the value of the variable?

Best Regards qweret

Share Improve this question asked Jan 4, 2013 at 11:45 qweretqweret 90210 silver badges17 bronze badges 1
  • check this thread, it contains the ansewrs link – Marcin Buciora Commented Jan 4, 2013 at 11:57
Add a ment  | 

2 Answers 2

Reset to default 5

You need to make an array of objects:

var array = [{key: 'a', value: 5}, {key: 'b', value: 10}, {key: 'c', value: 3}, {key: 'd', value: 10}, {key: 'e', value: 0}];

Then you apply a sort function:

array.sort(function(obj1, obj2) {
   return obj1.value - obj2.value;
});

Show the alert:

alert("This Variable has the lowest value: " + array[0].key); 

See it in action here.

as shown here use a sort function as an argument to the sort method call.

for example:

myArray.sort(myArraySortFunction);

function myArraySortFunction(a, b) {

}

you should take a look at javascript associative arrays as described here

本文标签: Javascript sort array of variables and return a variableStack Overflow