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
2 Answers
Reset to default 5You 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
版权声明:本文标题:Javascript sort array of variables and return a variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744099206a2533420.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论