4

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

1
  • check this thread, it contains the ansewrs link Commented Jan 4, 2013 at 11:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome! Worked like butter, thats exactly what i wanted. Didn't knew you could make such objects, but now that i know it, it sounds very logical! Thanks!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.