I would want to sort the values in multiple variables and still be able to call on the variable’s names (value1)
var value1 = 4
var value2 = 3
var value3 = 5
var value4 = 1
var value5 = 2
//This are the values that I want to sort//
How would I be able to sort these variables and still be able to call them using their names (value1)
Any help on this situation would be appreciated.
Can you also include an explanation of the code, I would be grateful.
2
Answers
You can sort your variables by putting them into an array an then using
.sort()
which sorts numbers by value.Hope this helps. 🙂
Edit: On the array I set the value to its own value but sorted. For future instances of code don’t modify original variables.
So this was an interesting one if I understand your question right. But basically, you can do this by lifting your variables up into an object like so:
With that in place, they now have names! So you can use
Object
to help yourself out:This sorts the values of the values and the names of the object, and then matches them up. Which results in:
So now you can call
data.value1
to get the value1 out as you indicated in your question and get a value that has been sorted into it.This feels like an xy problem question to me though. What are you actually trying to do because sorting an array is a google search away and not an appropriate question for this site.